Sending SMS to selected users from Gridview binded with Database

In last post i describe the simplest code that how to send SMS to used but now i am describing that how to send SMS to selected users from list of users from Gridview which is binded with database.

Intresting things for beginners are:

  1. How to bind Gridview with SQL Server Database?
  2. How to use Template Field (Header Template and Item Template)?
  3. How to use Checkbox in Gridview?
  4. Use of Check All checkbox in Gridview.
  5. How to get Gridview columns values on Button click which is outside Grid?
  6. How to send SMS on selected users from Gridview?

Binding Gridview from Database:

Use similar connectionstring in web.config file:

    <add name="ConStr" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\MessageDB.mdf;Integrated Security=True;User Instance=True"
     providerName="System.Data.SqlClient" />

And on code behind use the below code to bind Gridview:

private void fillgrid()
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
        SqlDataAdapter da = new SqlDataAdapter("Select * from message", con);
        DataTable dt = new DataTable();
        grdview.DataSource = dt;

Use of Template field and how to bind data on Template field:

<asp:GridView ID="grdview" runat="server" AutoGenerateColumns="False"
            Width="382px" BackColor="White" BorderColor="#336666" BorderStyle="Double"
            BorderWidth="3px" CellPadding="4" GridLines="Horizontal">
                        Select All
                        <asp:CheckBox ID="cbSelectAll" runat="server" onclick="checkAll(this);" />
                        <asp:CheckBox ID="chkSelect" runat="server" onclick="Check_Click(this)" />
                    <ItemStyle HorizontalAlign="Right" />
                <asp:TemplateField HeaderText="Applicant Name">
                        <asp:Label ID="Label1" runat="server" Text='<%# Bind("name") %>'></asp:Label>
                    <ItemStyle HorizontalAlign="Center" />
                <asp:TemplateField HeaderText="Mobile No.">
                        <asp:Label ID="Label2" runat="server" Text='<%# Bind("phone") %>'></asp:Label>
                    <ItemStyle HorizontalAlign="Center" />
            <FooterStyle BackColor="White" ForeColor="#333333" />
            <HeaderStyle BackColor="#336666" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#336666" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="White" ForeColor="#333333" />
            <SelectedRowStyle BackColor="#339966" Font-Bold="True" ForeColor="White" />
            <SortedAscendingCellStyle BackColor="#F7F7F7" />
            <SortedAscendingHeaderStyle BackColor="#487575" />
            <SortedDescendingCellStyle BackColor="#E5E5E5" />
            <SortedDescendingHeaderStyle BackColor="#275353" />
        <br />
        <asp:Button ID="btnSendMessage" runat="server" onclick="btnSendMessage_Click"
            Text="Send Message" />

Chekboxes in GridView:
Added checkbox in Gridview Item Template as well as Header Template. and below is the JAVAScript using for Check/Uncheck All checkboxes.

<script type = "text/javascript">
        function checkAll(objRef) {
            var GridView = objRef.parentNode.parentNode.parentNode;
            var inputList = GridView.getElementsByTagName("input");
            for (var i = 0; i < inputList.length; i++) {
                //Get the Cell To find out ColumnIndex
                var row = inputList[i].parentNode.parentNode;
                if (inputList[i].type == "checkbox" && objRef != inputList[i]) {
                    if (objRef.checked) {
                        //If the header checkbox is checked
                        //check all checkboxes
                        //and highlight all rows
                        inputList[i].checked = true;
                    else {
                        //If the header checkbox is checked
                        //uncheck all checkboxes
                        //and change rowcolor back to original                        
                        inputList[i].checked = false;
    <script type = "text/javascript">
        function Check_Click(objRef) {
            //Get the Row based on checkbox
            var row = objRef.parentNode.parentNode;           
            //Get the reference of GridView
            var GridView = row.parentNode;
            //Get all input elements in Gridview
            var inputList = GridView.getElementsByTagName("input");
            for (var i = 0; i < inputList.length; i++) {
                //The First element is the Header Checkbox
                var headerCheckBox = inputList[0];
                //Based on all or none checkboxes
                //are checked check/uncheck Header Checkbox
                var checked = true;
                if (inputList[i].type == "checkbox" && inputList[i] != headerCheckBox) {
                    if (!inputList[i].checked) {
                        checked = false;
            headerCheckBox.checked = checked;

Sending SMS to selected Users from Gridview:

Below is the sample code on Send Button click to send SMS to selected users:

protected void btnSendMessage_Click(object sender, EventArgs e)
        int success = 0;
        foreach (GridViewRow row in grdview.Rows)
            string senderusername = "xxxxx";
            string senderpassword = "xxxx";
            string senderid = "xxx";     
            Label _lblName, _lblMobile;
            CheckBox CheckBox1 = row.FindControl("chkSelect") as CheckBox;
            //Checking for the checkbox is checked or not
            if (CheckBox1.Checked == true)
                _lblName = row.FindControl("Label1") as Label;
                _lblMobile = row.FindControl("Label2") as Label;
                string mobile = _lblMobile.Text;
                string message = "Hello " + _lblName.Text;
                //**************** Send Message *******************************************
                string sURL;
                StreamReader objReader;
                sURL = "" + senderusername + "&api_password=" + senderpassword + "&sender=" + senderid  + "&to=" + mobile + "&message=" + message + "&priority=1";
                WebRequest wrGETURL;
                wrGETURL = WebRequest.Create(sURL);
                    Stream objStream;
                    objStream = wrGETURL.GetResponse().GetResponseStream();
                    objReader = new StreamReader(objStream);
                    success = 1;
                catch (Exception ex)
                    success = 0;
        if (success == 1)
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Messages send successfully');", true);
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error on sending messages..');", true);

FYI: Don't forgot to add below namespaces:

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

Note: In this example i am using API from and it is applicable for INDIA only your SMS providers and their API might be different.

Below is the screenshot of Grid and sample code also included as Attachment.

Sending SMS to selected users from Gridview binded with Database

Sample Code


No Comments

Add a Comment