Use RenderControl to save the HTML output of a Asp.Net DataGrid

Sunday, January 18, 2004
The following code sample demonstrates how you can save the HTML produced by a web form’s DataGrid control using the RenderControl method. Once you have the string of HTML you can easily save it as a file or email the result to a user. In the following example there is a web form with a DataGrid and Button control. When the user clicks the button the same DataGrid that appears on the screen will appear in an email.


private void Page_Load(object sender, System.EventArgs e)
{
   if(!IsPostBack)
   {
      SqlConnection sqlConnection;
      sqlConnection= new SqlConnection(CONNECTION_STRING);
      sqlConnection.Open();

      SqlCommand sqlCommand = new SqlCommand(
                                     SQLQUERY,
                                     sqlConnection
                                   );

      SqlDataReader sqlReader = null;
      try
      {
         sqlReader = sqlCommand.ExecuteReader(CommandBehavior.CloseConnection);

         DataGrid1.DataSource = sqlReader; 
         DataGrid1.DataBind();
      }
      finally
      {
         if(sqlReader != null)
            sqlReader.Close();
      }
   }  
}

private void Button1_Click(object sender, System.EventArgs e)
{         
   SendEmail(GetGridHtml());     
}

private string GetGridHtml()
{
   string result = null;

   StringWriter stringWriter = new StringWriter();
   HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
   
   try
   {
      htmlWriter.RenderBeginTag(HtmlTextWriterTag.Html);
      htmlWriter.RenderBeginTag(HtmlTextWriterTag.Body);         
      DataGrid1.RenderControl(htmlWriter);
      htmlWriter.RenderEndTag();
      htmlWriter.RenderEndTag();
      htmlWriter.Flush();

      result = stringWriter.ToString();
   }
   finally
   {
      htmlWriter.Close();
      stringWriter.Close();
   }
   return result;
}

private void SendEmail(string html)
{
   MailMessage mailMessage = new MailMessage();
   mailMessage.To = TOADDRESS;
   mailMessage.From = FROMADDRESS;
   mailMessage.Subject = SUBJECT;
   mailMessage.BodyFormat = MailFormat.Html;
   mailMessage.Body = html;
   SmtpMail.SmtpServer = SMTPSERVER;
   SmtpMail.Send(mailMessage);
}

by K. Scott Allen K.Scott Allen
My Pluralsight Courses
The Podcast!