Send Gridview Data in Mail Using Asp.net
Send Gridview Data in Mail Using Asp.net
Step 1: Design web form .aspx page
<div>
<asp:TextBox ID="mail_to"
runat="server"
placeholder="Enter
e-mail id"></asp:TextBox>
<br />
<br />
<br />
<asp:GridView ID="gr" runat="server"
AutoGenerateColumns="false"
AlternatingRowStyle-BackColor="WhiteSmoke"
Width="40%">
<HeaderStyle
BackColor="#3366ff"
Font-Bold="true"
ForeColor="White"
/>
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lbl_Name"
runat="server"
Text='<%#Eval("Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="City"
HeaderText="City"
/>
<asp:TemplateField HeaderText="Phone">
<ItemTemplate>
<asp:Label ID="lbl_phone"
runat="server"
Text='<%#Eval("Phone") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Button ID="btn_mail"
runat="server"
Text="Send
Mail" OnClick="btn_mail_Click"
BackColor="YellowGreen"
/>
</div>
Step 2: Logic on .CS page
Namespace:
using System.Net.Mail;
protected void Page_Load(object sender, EventArgs
e)
{
bind_gr();
}
public void bind_gr()
{
DataTable dt = new
DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("City");
dt.Columns.Add("Phone");
dt.Rows.Add("Kandy", "Delhi", "8802***2564");
dt.Rows.Add("Sam", "Hr", "545502*2544");
dt.Rows.Add("Izhar", "Up", "95802*2452");
dt.Rows.Add("Vineet", "Delhi", "88022564***");
dt.Rows.Add("Kandy", "Delhi", "8802***2564");
dt.Rows.Add("Sam", "Hr", "545502*2544");
dt.Rows.Add("Izhar", "Up", "95802*2452");
dt.Rows.Add("Vineet", "Delhi", "88022564***");
gr.DataSource = dt;
gr.DataBind();
}
protected void
btn_mail_Click(object sender, EventArgs e)
{
SendHTMLMail();
}
public void
SendHTMLMail()
{
MailMessage Msg = new
MailMessage();
MailAddress fromMail = new
MailAddress("no-reply@fromyourmailaddress.com");
Msg.From = fromMail;
Msg.To.Add(new MailAddress(mail_to.Text));
Msg.Subject = "Thats My Gridview";
Msg.Body += "Knady
<br/><br/>";
Msg.Body += GetGridviewData(gr);
Msg.IsBodyHtml = true;
SmtpClient smtp = new
SmtpClient("smtp.
fromyourmailaddress.com");
smtp.Host = "smtp. fromyourmailaddress.com";
smtp.Port = 25;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
NetworkCredential nc = new
NetworkCredential("no-reply@
fromyourmailaddress.com", "noreply@password");
smtp.Credentials = nc;
smtp.Send(Msg);
smtp.Timeout = 1000;
}
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)
{
}
Comments
Post a Comment