Please disable your adblock and script blockers to view this page
 

Send email to multiple users based on CheckBox selection inside GridView in asp.net C#,VB.Net

Introduction: In previous articles i explained How to send emails in asp.net using Gmail and How to send emails in asp.net | How to set Smtp setting in web.config file to send email in asp.net and Send emails in asp.net using Gmail | How to set Smtp setting in web.config file to send emails in asp.net using Gmail in asp.net and Delete multiple records from asp.net gridview with checkbox selection and  Show tool tip message using CSS and HTML and Highlight gridview row on mouse over using CSS and How to get CheckBoxList selected items in comma separated format in asp.net(C#,VB) and Fill CheckBoxList based on DropDownList selection in asp.net(C#, VB).
In this article I am going to explain with example How to send mail to multiple users based on CheckBox selection inside GridView. I have also implemented the Select/Unselect all CheckBoxes inside GridView in this article.

Send Mail to multiple users based on CheckBox Selection inside GridView in asp.net
click on image to enlarge
Implementation: Let;s create a sample application to see it in action.
  • Send Mail to multiple users based on CheckBox Selection inside GridView in asp.net
    Click on image to enlarge
    First of all create a Database e.g. "MyDataBase" and a table under that DataBase in Sql Server and name it "EMPLOYEE" as shown in figure: 



Note: EMP_ID column is set to Primary key and Identity specification is set to yes with Identity increment and Identity seed equal to 1. Insert some data in this table that you want to show in the Gridview.

  • Now in web.config file add the connection string under <configuration> tag as:
                <connectionStrings>
    <add name="conStr" connectionString="Data Source=LALIT;Initial Catalog=MyDataBase;Integrated Security=True"/>
  </connectionStrings>

Note: Replace the Data Source and the Initial Catalog(i.e. Database Name) as per your application.
  • Add a GridView and a Button control in design page of your asp.net website under <BODY> tag
Source Code:

<fieldset style="width:515px;">
            <legend>Send Mail to multiple users based on CheckBox Selection inside GridView in asp.net</legend>
            <table>
                <tr>
                    <td>
                        <asp:GridView ID="grEmp" runat="server" AllowPaging="True" AutoGenerateColumns="False"
                   DataKeyNames="EMP_ID" GridLines="None" Width="100%" CellPadding="4" ForeColor="#333333">
                   
                    <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                   
                    <Columns>
                        <asp:BoundField DataField="EMP_ID" HeaderText="EMP_ID" Visible="False" />
                        <asp:BoundField DataField="EMP_NAME" HeaderText="Emp Name"  />
                        <asp:BoundField DataField="DEPT" HeaderText="Department"  />
                        <asp:BoundField DataField="SALARY" HeaderText="salary"  />
                        <asp:BoundField DataField="EMAIL_ID" HeaderText="Email Id" />                                          
                     
                     <asp:TemplateField HeaderText="CheckAll">
                    <HeaderTemplate>
                        <asp:CheckBox ID="chkSelectAll" runat="server"
                                      AutoPostBack="true"
                                      OnCheckedChanged="chkSelectAll_CheckedChanged"/>Send Mail To All ?
                    </HeaderTemplate>
                        <ItemTemplate>
                        <asp:CheckBox ID="chkSelect" runat="server"/>
                        </ItemTemplate>
                     </asp:TemplateField>
                    </Columns>                  
                    <EditRowStyle BackColor="#999999" />
                    <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                    <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                    <SortedAscendingCellStyle BackColor="#E9E7E2" />
                    <SortedAscendingHeaderStyle BackColor="#506C8C" />
                    <SortedDescendingCellStyle BackColor="#FFFDF8" />
                    <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
                </asp:GridView>
                    </td>
                </tr>
                </table>
            <asp:Button ID="btnSendMail" runat="server" Text="Send Email" OnClick="btnSendMail_Click" /> 
        </fieldset>

C#.Net Code to send emails to multiple users 

First include the following namespaces

using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Net;
using System.Net.Mail;

then write the code as:

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindEmpGrid();
        }
    }

    protected void BindEmpGrid()
    {      
        SqlCommand cmd = new SqlCommand("select * from EMPLOYEE", con);
        DataTable dt = new DataTable();
        SqlDataAdapter adp = new SqlDataAdapter(cmd);
        adp.Fill(dt);
        grEmp.DataSource = dt;
        grEmp.DataBind();
    }

    protected void btnSendMail_Click(object sender, EventArgs e)
    {
        string empId = string.Empty;
        DataTable dt = new DataTable();
        try
        {
            foreach (GridViewRow row in grEmp.Rows)
            {
                CheckBox cb = (CheckBox)row.FindControl("chkSelect");

                if (cb.Checked == true)
                {
                    if (cb != null && cb.Checked)
                    {
                        //get Current EMAIL_ID from the DataKey
                        empId = Convert.ToString(grEmp.DataKeys[row.RowIndex].Value);
                        SqlCommand cmd = new SqlCommand("select EMAIL_ID from EMPLOYEE where EMP_ID=" + empId + "", con);
                        SqlDataAdapter adp = new SqlDataAdapter(cmd);
                        //Fill datatable with EMAIL_ID corresponding to Current EMP_ID
                        adp.Fill(dt);
                        //Get EMAIL_ID into variable
                        string emailId = dt.Rows[0]["EMAIL_ID"].ToString();
                        //write code to send mail
                        SendEmailUsingGmail(emailId);
                        dt.Clear();
                        dt.Dispose();
                    }                  
                }
            }
            ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Emails sent successfully');", true);
        }
        catch (Exception ex)
        {
            Response.Write("Error occured: " + ex.Message.ToString());
        }
        finally
        {
            empId = string.Empty;           
        }
    }

    private void SendEmailUsingGmail(string toEmailAddress)
    {
        try
        {
            SmtpClient smtp = new SmtpClient();
            smtp.Credentials = new NetworkCredential("YourGmailEmailID", "YourGmailPassword");
            smtp.Port = 587;
            smtp.Host = "smtp.gmail.com";
            smtp.EnableSsl = true;
            MailMessage message = new MailMessage();
            message.From = new MailAddress("YourGmailEmailID");
            message.To.Add(toEmailAddress);
            message.Subject = "Write your email subject here";
            message.Body = "write the content of the email here";
            smtp.Send(message);          
        }
        catch(Exception ex)
        {
            Response.Write("Error occured: " + ex.Message.ToString());
        }
    }

    protected void chkSelectAll_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox chkAll =
           (CheckBox)grEmp.HeaderRow.FindControl("chkSelectAll");
        if (chkAll.Checked == true)
        {
            foreach (GridViewRow gvRow in grEmp.Rows)
            {
                CheckBox chkSel =
                     (CheckBox)gvRow.FindControl("chkSelect");
                chkSel.Checked = true;              
            }
        }
        else
        {
            foreach (GridViewRow gvRow in grEmp.Rows)
            {
                CheckBox chkSel = (CheckBox)gvRow.FindControl("chkSelect");
                chkSel.Checked = false;              
            }
        }  
    }

VB.Net Code to send emails to multiple users

First import the following namespaces:

Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Net
Imports System.Net.Mail

Then write the code as:

  Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("conStr").ConnectionString)

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            BindEmpGrid()
        End If
    End Sub

    Protected Sub BindEmpGrid()
        Dim cmd As New SqlCommand("select * from EMPLOYEE", con)
        Dim dt As New DataTable()
        Dim adp As New SqlDataAdapter(cmd)
        adp.Fill(dt)
        grEmp.DataSource = dt
        grEmp.DataBind()
    End Sub

    Protected Sub btnSendMail_Click(sender As Object, e As EventArgs)
        Dim empId As String = String.Empty
        Dim dt As New DataTable()
        Try
            For Each row As GridViewRow In grEmp.Rows
                Dim cb As CheckBox = DirectCast(row.FindControl("chkSelect"), CheckBox)

                If cb.Checked = True Then
                    If cb IsNot Nothing AndAlso cb.Checked Then
                        'get Current EMAIL_ID from the DataKey
                        empId = Convert.ToString(grEmp.DataKeys(row.RowIndex).Value)
                        Dim cmd As New SqlCommand("select EMAIL_ID from EMPLOYEE where EMP_ID=" & empId & "", con)
                        Dim adp As New SqlDataAdapter(cmd)
                        'Fill datatable with EMAIL_ID corresponding to Current EMP_ID
                        adp.Fill(dt)
                        'Get EMAIL_ID into variable
                        Dim emailId As String = dt.Rows(0)("EMAIL_ID").ToString()
                        'write code to send mail
                        SendEmailUsingGmail(emailId)
                        dt.Clear()
                        dt.Dispose()
                    End If
                End If
            Next
            ScriptManager.RegisterClientScriptBlock(Page, Page.[GetType](), Guid.NewGuid().ToString(), "alert('Emails sent successfully');", True)
        Catch ex As Exception
            Response.Write("Error occured: " & ex.Message.ToString())
        Finally
            empId = String.Empty
        End Try
    End Sub

    Private Sub SendEmailUsingGmail(toEmailAddress As String)
        Try
            Dim smtp As New SmtpClient()
            smtp.Credentials = New NetworkCredential("YourGmailEmailID", " YourGmailPassword")
            smtp.Port = 587
            smtp.Host = "smtp.gmail.com"
            smtp.EnableSsl = True
            Dim message As New MailMessage()
            message.From = New MailAddress("YourGmailEmailID")
            message.[To].Add(toEmailAddress)
            message.Subject = "Write your email subject here"
            message.Body = "write the content of the email here"
            smtp.Send(message)
        Catch ex As Exception
            Response.Write("Error occured: " & ex.Message.ToString())
        End Try
    End Sub

    Protected Sub chkSelectAll_CheckedChanged(sender As Object, e As EventArgs)
        Dim chkAll As CheckBox = DirectCast(grEmp.HeaderRow.FindControl("chkSelectAll"), CheckBox)
        If chkAll.Checked = True Then
            For Each gvRow As GridViewRow In grEmp.Rows
                Dim chkSel As CheckBox = DirectCast(gvRow.FindControl("chkSelect"), CheckBox)
                chkSel.Checked = True
            Next
        Else
            For Each gvRow As GridViewRow In grEmp.Rows
                Dim chkSel As CheckBox = DirectCast(gvRow.FindControl("chkSelect"), CheckBox)
                chkSel.Checked = False
            Next
        End If
    End Sub
End Class

Now over to you:

"If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates."
Previous
Next Post »

18 comments

Click here for comments
Anonymous
admin
August 10, 2013 ×

very nice article...thank you and keep posting..
Sir..can you please send a complete tutorial starting from basic for WCF..
I would be thakfull

Reply
avatar
Asif Khan
admin
August 10, 2013 ×

very nice article...thank you and keep posting..
Sir..can you please send a complete tutorial starting from basic for WCF..
I would be thakfull

Reply
avatar
August 11, 2013 ×

Thanks for the appreciation..
Read the below articles to have the knowledge on wcf services

How to create and consume WCF Services in asp.net ?
http://www.webcodeexpert.com/2013/04/how-to-create-and-consume-wcf-services.html

&

WCF Service to bind,insert,edit,update,delete from sql server database in asp.net C#
http://www.webcodeexpert.com/2013/08/wcf-service-to-bindinserteditupdatedele.html

Reply
avatar
August 11, 2013 ×

How to create and consume WCF Services in asp.net ?
http://www.webcodeexpert.com/2013/04/how-to-create-and-consume-wcf-services.html
&
WCF Service to bind,insert,edit,update,delete from sql server database in asp.net C#
http://www.webcodeexpert.com/2013/08/wcf-service-to-bindinserteditupdatedele.html

Reply
avatar
kebhari
admin
September 07, 2013 ×

very nice post.

Reply
avatar
September 08, 2013 ×

stay tuned and stay connected for more updates..

Reply
avatar
king
admin
September 27, 2013 ×

dear sir i m the new user in the development world

plz provide me the best way to i starting my development

thanks

Reply
avatar
September 27, 2013 ×

Hi king..you can learn online or join any training institute..obviously keep reading my blog and you will learn more and more...:)

Reply
avatar
king
admin
September 27, 2013 ×

dear sir i added u in google plus also plz can u me some basic notes with example with written in ur language thanks

Reply
avatar
September 28, 2013 ×

Error occured: The multi-part identifier "email id where sending email" could not be bound.

Please find the error.

Reply
avatar
September 28, 2013 ×

Hello Ankit..i think your are missing something i n your code..so i suggest you to recheck your code and try once more..if still you face error then let me know..i will help you to sort out the error..

Reply
avatar
September 28, 2013 ×

check and match for the sql queries with this articles too..

Reply
avatar
Anand Bajpai
admin
October 18, 2013 ×

its not working

Reply
avatar
October 18, 2013 ×

Hello Anand Bajpai..what problem your are facing? Please mentioned the exact error/exception that your are facing?

Reply
avatar
January 07, 2014 ×

sir i am try to send email but error is :-Error occured: The specified string is not in the form required for an e-mail address. pls help me

Reply
avatar
January 07, 2014 ×

Hello Arjun Walmiki..please check your email address format..if still you are facing problem then let me know..i will help you..

Reply
avatar
March 01, 2014 ×

Where can i compose the message to send in their Email?

Reply
avatar

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily.. ConversionConversion EmoticonEmoticon