This articles explains about how to send an content of a grid view through email to multiple recipients email .
Introduction
This articles explains about how to send an content of a
gridview through email to multiple recipients email .
Objective
To get the basic idea sending a content of a gridview
through email to multiple recepients.
Using the code
Here I am using two pages in my application.
.Pag1.aspx-Used to send the details of the person (any specific
User) using Querystring mechanism.
.Page2.aspx-To view the
details of the user in a gridview
// write code here
<head runat="server">
<title></title>
<script type="text/javascript" language="javascript">
function validate() {
var x = document.getElementById('txtCustomerID');
if (x.value == '') {
alert('Please enter the User Name');
return false;
}
else {
return true;
}
}
</script>
</head>
//Under page design i have used an client side validation for validating
the empty fields of the person name
<script type="text/javascript" language="javascript">
function validate() {
var x = document.getElementById('txtCustomerID');
if (x.value == '') {
alert('Please enter the User Name');
return false;
}
else {
return true;
}
}
</script>
/
/The below page design specifies the controls used.<body>
<form id="form1" runat="server">
<div>
<table align="center" id="tbl1" runat="server">
<tr>
<td>
Enter Customer Name
</td>
<td>
<asp:TextBox ID="txtCustomerID" runat="server" Height="20px" Width="128px"></asp:TextBox>
</td>
</tr>
<tr>
<td></td>
<td>
<asp:Button ID="btnSend" runat="server" Text="Send Email" class="mybutton"
onclick="btnAddtoList_Click" OnClientClick="return validate()" ValidationGroup="v1" />
</td>
</tr>
</table>
</div>
</form>
</body>
The below line specifies the connection string to connect it to database
string Conn = ConfigurationManager.ConnectionStrings["MyDBConnection"].ConnectionString;
//The below is an button click event with querystring concept which
populates the names from the //tbl_Registration table whose details can be viewed
in a gridview control and send it as an email from //page2.aspx
protected void btnSend_Click(object sender, EventArgs e)
{
string Serial = txtCustomerID.Text.Trim();
SqlConnection cnn = new SqlConnection(Conn);
SqlCommand cmd = new SqlCommand("select * from tbl_registrations where Name='" + Serial + "' ", cnn);
SqlDataAdapter ada = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
ada.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
Response.Redirect("SendEmails.aspx?Name="+Serial+"");
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "Alert", "alert('No User exist');", true);
}
}
//Here is conclusion of page1.aspx’s functionality once the users clicks a
button the control reflects to //another page i.e:page2.aspx.
Page2’s.aspx
The below is an .aspx page design code with TextBox ,CheckboxList ,ListBox
and Gridview controls which are being used to view and send the details of the
User through email.
<table align="center">
<tr>
<td>
Name:
</td>
<td colspan="4">
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
</td>
</tr>
</table>
<table align="center">
<tr>
<td colspan="4">
<asp:CheckBoxList ID="CheckBoxList1" runat="server"
RepeatDirection="Horizontal"
AutoPostBack="True"
onselectedindexchanged="CheckBoxList1_SelectedIndexChanged1">
<asp:ListItem Text="Contact Details" Value="1"></asp:ListItem>
<asp:ListItem Text="Personal Details" Value="2"></asp:ListItem>
</asp:CheckBoxList>
</td>
</tr>
<tr>
<td>
</td>
</tr>
<tr>
<td>
<asp:GridView ID="grdContactDtls" DataKeyNames="Name" runat="server"
AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333"
GridLines="None" CellSpacing="2" Width="422px">
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<%#Eval("Name") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email">
<ItemTemplate>
<%#Eval("Email") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Residential Address">
<ItemTemplate>
<%#Eval("ResAddress") %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
<asp:GridView ID="grdPersonalDtls" runat="server" AutoGenerateColumns="False"
CellPadding="4" ForeColor="#333333" GridLines="None" CellSpacing="2"
Width="422px">
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<%#Eval("Name") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Marital Status">
<ItemTemplate>
<%#Eval("MaritalStatus") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Mobile">
<ItemTemplate>
<%#Eval("Mobile") %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
</td>
</tr>
</table>
<table align="center">
<tr>
<td>
Select Users to Send an Email:
</td>
<td colspan="2">
<asp:ListBox ID="ListBox1" runat="server"></asp:ListBox>
</td>
<td>
<asp:Button ID="Button1" runat="server" Text=">>" onclick="Button1_Click"
style="height: 26px" /><br />
<asp:Button ID="Button2"
runat="server" Text="<<" onclick="Button2_Click" />
</td>
<td colspan="2">
<asp:ListBox ID="ListBox2" runat="server"></asp:ListBox>
</td>
</tr>
<tr>
<td></td>
<td colspan="4">
<asp:Button ID="btnSendMails" runat="server" Text="Send Email"
onclick="btnSendMails_Click" />
</td>
</tr>
</table>
Code Behind (.cs)
using System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Web;
using
System.Web.UI;
using
System.Web.UI.WebControls;
using
System.Data;
using
System.Data.SqlClient;
using
System.Configuration;
using
System.Collections;
using
System.Net.Mail;
using
System.Text;
using System.IO;
Using The Code
//The below line specifies the connection string to connect it to database
string Conn =
ConfigurationManager.ConnectionStrings["MyDBConnection"].ConnectionString;
string Name;
Page Load Method
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillListBox();//User Defined method to Fill the list users
if (Request.QueryString["Name"] != null)//checks for Querystring is not null
{
FillGrid();
}
}
}
protected void FillGrid()
{
Name = Request.QueryString["Name"].ToString();
txtName.Text = Name.ToString().ToUpper();
SqlConnection cnn = new SqlConnection(Conn);
SqlCommand cmd = new SqlCommand("select Email from tbl_registrations where Name='"+Name+"'", cnn);
SqlDataAdapter ada = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
ada.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
}
}
//User defined method for Filling the checkbox list controls
protected void FillListBoxControls()
{
SqlConnection cnn = new SqlConnection(Conn);
SqlCommand cmd = new SqlCommand("select * from tblDtls", cnn);
SqlDataAdapter ada = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
ada.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
CheckBoxList1.DataSource = ds.Tables[0];
CheckBoxList1.DataTextField = "Name";
CheckBoxList1.DataValueField = "id";
CheckBoxList1.DataBind();
}
else
{
}
}
//User defined method for filling up the Listbox 1 with UserNames whome to send an email
protected void FillListBox()
{
SqlConnection cnn = new SqlConnection(Conn);
SqlCommand cmd = new SqlCommand("select Name from tbl_REgistrations", cnn);
SqlDataAdapter ada = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
ada.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
ListBox1.DataSource = ds.Tables[0];
ListBox1.DataTextField = "Name";
ListBox1.DataBind();
}
else
{
}
}
//The below button click event of button 1 is used to fill the listbox2 with the list of names //whome the user wish to send an email
protected void Button1_Click(object sender, EventArgs e)
{
if (ListBox1.SelectedIndex > -1)
{
System.Web.UI.WebControls.ListItem Li = new System.Web.UI.WebControls.ListItem(ListBox1.SelectedItem.Text);
if (!ListBox2.Items.Contains(Li))
{
ListBox2.Items.Add(ListBox1.SelectedItem.Text);
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "Alert", "alert('User already exists');", true);
}
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "Alert", "alert('Select any user to add');", true);
}
}
//The below button click event of button 2 is used to remove the users if nt necessary to send an email
protected void Button2_Click(object sender, EventArgs e)
{
if (ListBox2.SelectedIndex > -1)
{
ListBox2.Items.Remove(ListBox2.SelectedItem.Text);
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "Alert", "alert('Select any user to remove');", true);
}
}
//User Defined method to fill contact details of the user and bind it in a grdContactDtls
protected void FillContactDtls(string Name)
{
SqlConnection cnn = new SqlConnection(Conn);
SqlCommand cmd = new SqlCommand("select Name,Email,ResAddress from tbl_Registrations where Name='"+Name+"'", cnn);
SqlDataAdapter ada = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
ada.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
grdContactDtls.Visible = true;
grdContactDtls.DataSource = ds;
grdContactDtls.DataBind();
}
else
{
}
}
//User Defined method to fill personal details of the user and bind it in a grdPersonalDtls
protected void FillPersnlDtls(string Name)
{
SqlConnection cnn = new SqlConnection(Conn);
SqlCommand cmd = new SqlCommand("select Name,MaritalStatus,Mobile from tbl_Registrations where Name='" + Name + "'", cnn);
SqlDataAdapter ada = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
ada.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
grdPersonalDtls.Visible = true;
grdPersonalDtls.DataSource = ds;
grdPersonalDtls.DataBind();
}
else
{
}
}
//The CheckBoxList selected Index change event is used to display the contact and personal //details of the user in an gridview
protected void CheckBoxList1_SelectedIndexChanged1(object sender, EventArgs e)
{
Name = Request.QueryString["Name"].ToString();
SqlConnection cnn = new SqlConnection(Conn);
SqlCommand cmd = new SqlCommand("select * from tblDtls", cnn);
SqlDataAdapter ada = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
ada.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < CheckBoxList1.Items.Count; i++)
{
if (CheckBoxList1.Items[i].Selected == true)
{
if(CheckBoxList1.Items[i].Text=="Contact Details")
{
FillContactDtls(Name);
}
else if (CheckBoxList1.Items[i].Text == "Personal Details")
{
FillPersnlDtls(Name);
}
}
else if (CheckBoxList1.Items[i].Selected == false)
{
if (CheckBoxList1.Items[i].Text == "Contact Details")
{
grdContactDtls.Visible = false;
}
else if (CheckBoxList1.Items[i].Text == "Personal Details")
{
grdPersonalDtls.Visible = false;
}
}
}
}
}
//The send mails button click event is used to send the content of a gridview to the list of //users under listBox2
protected void btnSendMails_Click(object sender, EventArgs e)
{
for (int i = 0; i < CheckBoxList1.Items.Count; i++)
{
if ((CheckBoxList1.Items[i].Selected == false) && (ListBox2.SelectedIndex ==-1))
{
ClientScript.RegisterStartupScript(this.GetType(), "Alert", "alert('Please select the users and contact details to send a mail');", true);
}
else
{
ArrayList UserEmail = new ArrayList();
string Email = string.Empty;
string B;
for (int ii = 0; ii < ListBox2.Items.Count; ii++)
{
string Name = ListBox2.Items[ii].Text;
SqlConnection cnn = new SqlConnection(Conn);
SqlCommand cmd = new SqlCommand("select Email from tbl_Registrations where Name='" + Name + "'", cnn);
SqlDataAdapter ada = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
ada.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
UserEmail.Add(ds.Tables[0].Rows[0]["Email"].ToString());
}
}
for (int j = 0; j < UserEmail.Count; j++)
{
Email += UserEmail[j].ToString() + ",";
}
B = fnAttachGridView();
MyMail(Email, B, txtName.Text);
}
}
}
//The user defined method fnAttachGridView will attach the contact details of users of a gridview //in a string builder class to send an email
public string fnAttachGridView()
{
StringBuilder BB = new StringBuilder();
string SB = string.Empty;
for (int k = 0; k < CheckBoxList1.Items.Count; k++)
{
if (CheckBoxList1.Items[k].Selected == true)
{
if (CheckBoxList1.Items[k].Text == "Contact Details")
{
SB += grdContactDtlsToHtml(grdContactDtls);
}
else if (CheckBoxList1.Items[k].Text == "Personal Details")
{
SB += grdPersDtlsToHtml(grdPersonalDtls);
}
}
}
return SB; ;
}
//The below user defined method to attach the content of grdContactDtls in a string builder class
public string grdContactDtlsToHtml(GridView gvC)
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
Html32TextWriter hw = new Html32TextWriter(sw);
gvC.RenderControl(hw);
hw.Flush();
sw.Flush();
return sb.ToString(); ;
}
//The below user defined method to attach the content of grdPewrsonalDtls in a string builder class
public string grdPersDtlsToHtml(GridView gvC)
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
Html32TextWriter hw = new Html32TextWriter(sw);
gvC.RenderControl(hw);
hw.Flush();
sw.Flush();
return sb.ToString(); ;
}
//The below method is Used to Override the Render method to ensure that this control which is //nested in an HtmlForm server control, between a opening and closing of a form tag.
public override void VerifyRenderingInServerForm(Control control)
{
return;
}
//The below MyMail class is used to send an email with the conten of a gfridview to users
public void MyMail(string email, string msg, string subject)
{
string from="admin.a@gmail.com";
try
{
if (email != "" && from != "")
{
MailMessage m = new MailMessage();
m.From = new MailAddress(from);
m.To.Add(email);
m.IsBodyHtml = true;
m.Subject = "Sample Email "+ subject;
m.Body = msg;
SmtpClient smtp = new SmtpClient("localhost", 25);
smtp.Send(m);
m.Dispose();
}
}
catch (Exception ex)
{
Response.Write("alert('"+ex.Message+"')");
}
finally
{
}
}
Conclusion
The
main intention of this article is written due to some of the users need to send
an email with an attachment file to their recepients which I have made it.