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

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


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)
{
BindGridview();
}
}


// 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");
con.Open();
SqlCommand cmd = new SqlCommand("SELECT TOP 10 UserName,FirstName,LastName,Location FROM UserInformation", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvUserInfo.DataSource = ds;
gvUserInfo.DataBind();
}
protected void btnSendMail_Click(object sender, EventArgs e)
{
SendHTMLMail();
}


// 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("administrator@aspdotnet-suresh.com");
// Sender e-mail address.
Msg.From = fromMail;
// Recipient e-mail address.
Msg.To.Add(new MailAddress("suresh@gmail.com"));
// 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 = "10.2.160.101";
SmtpClient a = new SmtpClient();
a.Host = sSmtpServer;
a.EnableSsl = true;
a.Send(Msg);
}
// 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);
gv.RenderControl(htw);
return strBuilder.ToString();
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}

Comments or Responses

Login to post response