Home > ASP.Net > Send Gridview Content Through Email

Send Gridview Content Through Email


Hi all,

try this example to send Gridview content through email

In this example i will use Northwind Database to bind it to Gridview and it’s content through Email

1) Open VS2008 and create a new website and add new web page and from Toolbox drag Button and Gridview and bind it using SqlDataSouces control


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default"
 EnableEventValidation="false" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 <title>Untitled Page</title>
</head>
<body>
 <form id="form1" runat="server">
 <div>
 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
 DataKeyNames="ProductID" DataSourceID="SqlDataSource1" ForeColor="#333333">
 <RowStyle BackColor="#EFF3FB" />
 <Columns>
 <asp:BoundField DataField="ProductID" HeaderText="ProductID" InsertVisible="False"
 ReadOnly="True" SortExpression="ProductID" />
 <asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName" />
 <asp:BoundField DataField="QuantityPerUnit" HeaderText="QuantityPerUnit" SortExpression="QuantityPerUnit" />
 <asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" SortExpression="UnitPrice" />
 <asp:TemplateField HeaderText="Discontinued" SortExpression="Discontinued">
 <ItemTemplate>
 <asp:CheckBox ID="CheckBox1" runat="server" Checked='<%# Bind("Discontinued") %>'
 Enabled="false" />
 </ItemTemplate>
 </asp:TemplateField>
 </Columns>
 <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
 <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
 <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
 <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
 <EditRowStyle BackColor="#2461BF" />
 <AlternatingRowStyle BackColor="White" />
 </asp:GridView>
 <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
 SelectCommand="SELECT [ProductID], [ProductName], [QuantityPerUnit], [UnitPrice], [Discontinued] FROM [Products]">
 </asp:SqlDataSource>
 <br />
 <asp:Button ID="btn_Send" runat="server" OnClick="btn_Send_Click" Text="Send Email" />
 </div>
 </form>
</body>
</html>

and in code behind add the following code :


using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Net.Mail;
using System.IO;
using System.Text;

public partial class _Default : System.Web.UI.Page
{
 #region Method
 private string GridViewToHtml(GridView gv)
 {
 StringBuilder SB = new StringBuilder();
 StringWriter SW = new StringWriter(SB);
 HtmlTextWriter htmlTW = new HtmlTextWriter(SW);
 gv.RenderControl(htmlTW);
 return SB.ToString();
 }

private bool SendMail(string from, string subject)
 {
 try
 {
 string mailServerName = "smtp.gmail.com";
 string body = GridViewToHtml(GridView1);
 MailMessage message = new MailMessage(from, "email@gmail.com", subject, body);
 message.IsBodyHtml = true;
 SmtpClient smtp = new SmtpClient();
 smtp.Host = mailServerName;
 smtp.Host = "smtp.gmail.com";
 smtp.EnableSsl = true;
 smtp.UseDefaultCredentials = true;
 System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
 NetworkCred.UserName = "email@gmail.com";
 NetworkCred.Password = "*****";
 smtp.UseDefaultCredentials = true;
 smtp.Credentials = NetworkCred;
 smtp.Port = 587;
 smtp.Send(message);
 }
 catch (Exception ex)
 {
 ClientScript.RegisterStartupScript(Type.GetType("System.String"), "messagebox", "<script type=\"text/javascript\">alert('An Error Accured try again.');</script>");
 }
 return true;
 }
 public override void VerifyRenderingInServerForm(Control control)
 {

}
 #endregion

protected void Page_Load(object sender, EventArgs e)
 {

}
 protected void btn_Send_Click(object sender, EventArgs e)
 {
 if (SendMail("noor3rb@hotmail.com", "Send Gridview in Email"))
 {
 // Sucess to send Email
 ClientScript.RegisterStartupScript(Type.GetType("System.String"), "messagebox", "<script type=\"text/javascript\">alert('Email has been sent.');</script>");
 }
 else
 {
 // Fail to send Email
 ClientScript.RegisterStartupScript(Type.GetType("System.String"), "messagebox", "<script type=\"text/javascript\">alert('An Error Accured try again.');</script>");
 }
 }
}

2) In Web.Config add connectionstring


<connectionStrings>
 <add name="NorthwindConnectionString" connectionString="Data Source=.;Initial Catalog=Northwind;Integrated Security=True" providerName="System.Data.SqlClient"/>
 </connectionStrings>

Hope this helps

Good Luck.

Categories: ASP.Net
  1. Suraj
    December 19, 2012 at 5:13 am

    Specified cast is not valid.(Error)

  2. June 30, 2014 at 5:22 pm

    Attractive section of content. I just stumbled upon your website and in accession capital to assert that I get in fact enjoyed account your blog posts.
    Any way I’ll be subscribing to your feeds and even I achievement you access
    consistently fast.

  3. September 20, 2014 at 8:36 pm

    Amazing! Its genuinely amazing article, I have got
    much clear idea regarding from this article.

  1. No trackbacks yet.

Leave a comment