How to Send Gridview in Email Body in Asp.Net Using C#

Posted by Rajesh081725 under C# category on | Points: 40 | Views : 7617
<html xmlns="">
<head id="Head1">
<title>send gridview in email body in using C#,VB.NET</title>
<form id="form1" runat="server">
<asp:GridView ID="gvUserInfo" runat="server">
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
<asp:Button ID="btnSendMail" runat="server" Text="Send Gridview As Mail" onclick="btnSendMail_Click" />

using System;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Net.Mail;
using System.Text;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;

After add namespaces write the following code in code behind

protected void Page_Load(object sender, EventArgs e)
if (!IsPostBack)

// This method is used to bind gridview from database
protected void BindGridview()
SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB");
SqlCommand cmd = new SqlCommand("SELECT TOP 10 UserName,FirstName,LastName,Location FROM UserInformation", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
gvUserInfo.DataSource = ds;
protected void btnSendMail_Click(object sender, EventArgs e)

// Method Which is used to Get HTML File and replace HTML File values with dynamic values and send mail
public void SendHTMLMail()
MailMessage Msg = new MailMessage();
MailAddress fromMail = new MailAddress("");
// Sender e-mail address.
Msg.From = fromMail;
// Recipient e-mail address.
Msg.To.Add(new MailAddress(""));
// Subject of e-mail
Msg.Subject = "Send Gridivew in EMail";
Msg.Body += "Please check below data <br/><br/>";
Msg.Body += GetGridviewData(gvUserInfo);
Msg.IsBodyHtml = true;
string sSmtpServer = "";
sSmtpServer = "";
SmtpClient a = new SmtpClient();
a.Host = sSmtpServer;
a.EnableSsl = true;
// This Method is used to render gridview control
public string GetGridviewData(GridView gv)
StringBuilder strBuilder = new StringBuilder();
StringWriter strWriter = new StringWriter(strBuilder);
HtmlTextWriter htw = new HtmlTextWriter(strWriter);
return strBuilder.ToString();
public override void VerifyRenderingInServerForm(Control control)
/* Verifies that the control is rendered */

Comments or Responses

Login to post response