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:
- How to bind Gridview with SQL Server Database?
- How to use Template Field (Header Template and Item Template)?
- How to use Checkbox in Gridview?
- Use of Check All checkbox in Gridview.
- How to get Gridview columns values on Button click which is outside Grid?
- How to send SMS on selected users from Gridview?
Binding Gridview from Database:
Use similar connectionstring in web.config file:
<connectionStrings>
<add name="ConStr" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\MessageDB.mdf;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
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();
da.Fill(dt);
grdview.DataSource = dt;
grdview.DataBind();
}
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">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
Select All
<asp:CheckBox ID="cbSelectAll" runat="server" onclick="checkAll(this);" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" onclick="Check_Click(this)" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Right" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Applicant Name">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("name") %>'></asp:Label>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Mobile No.">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("phone") %>'></asp:Label>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
</Columns>
<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" />
</asp:GridView>
<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>
<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;
break;
}
}
}
headerCheckBox.checked = checked;
}
</script>
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 = "http://sms.dunitech.com/pushsms.php?username=" + senderusername + "&api_password=" + senderpassword + "&sender=" + senderid + "&to=" + mobile + "&message=" + message + "&priority=1";
WebRequest wrGETURL;
wrGETURL = WebRequest.Create(sURL);
try
{
Stream objStream;
objStream = wrGETURL.GetResponse().GetResponseStream();
objReader = new StreamReader(objStream);
objReader.Close();
success = 1;
}
catch (Exception ex)
{
ex.ToString();
success = 0;
}
}
}
if (success == 1)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Messages send successfully');", true);
}
else
{
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 dunitech.com 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.
Sample Code