Description:
In this example we explain that how to select and
deselect all the record from gridview using javascript or jQuery.or how to
checked or unchecked all the records in gridview using javascript.
In previous we already explain that how to delete
multiple records form the gridview but here we use javascript to checked or
unchecked all the records from gridview without any postback.
So how to select/deselect all checkbox in gridview
in clientside using javascript or jQuery.below is the example to demostrate
checked/unchecked all records from griview using javascript.
Registration.aspx:
<%@
Page Language="C#" AutoEventWireup="true" CodeFile="Registration.aspx.cs" Inherits="Registration"
%>
<%@
Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit"
TagPrefix="cc1"
%>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function
Check_Click(objRef) {
var
row = objRef.parentNode.parentNode;
var
GridView = row.parentNode;
var
inputList = GridView.getElementsByTagName("input");
for
(var i = 0; i < inputList.length; i++) {
var
headerCheckBox = inputList[0];
var
checked = true;
if
(inputList[i].type == "checkbox"
&& inputList[i] != headerCheckBox) {
if
(!inputList[i].checked) {
checked = false;
break;
}
}
}
headerCheckBox.checked = checked;
}
function
checkAll(objRef) {
var
GridView = objRef.parentNode.parentNode.parentNode;
var
inputList = GridView.getElementsByTagName("input");
for
(var i = 0; i < inputList.length; i++) {
var
row = inputList[i].parentNode.parentNode;
if
(inputList[i].type == "checkbox"
&& objRef != inputList[i]) {
if
(objRef.checked) {
inputList[i].checked =
true;
}
else
{
if (row.rowIndex % 2 == 0) {
row.style.backgroundColor = "#C2D69B";
}
else {
row.style.backgroundColor = "white";
}
inputList[i].checked =
false;
}
}
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<fieldset>
<legend>Employee
Registration
</legend>
<div align="center">
<table>
<tr>
<td>Name :</td>
<td>
<asp:TextBox runat="server"
ID="txtname"
/>
<asp:RequiredFieldValidator
ID="RequiredFieldValidator1"
ForeColor="Red"
ErrorMessage="Please
Enter Name" Display="Dynamic" Text="*" ValidationGroup="Submit" ControlToValidate="txtname" runat="server" />
</td>
</tr>
<tr>
<td>DOB :</td>
<td>
<asp:TextBox runat="server"
ID="txtdob"
/>
<cc1:CalendarExtender ID="calendar1"
PopupButtonID="txtdob"
TargetControlID="txtdob"
Format="dd/MM/yyyy"
runat="server"></cc1:CalendarExtender>
<asp:RequiredFieldValidator
ID="requiredfieldvalidator2"
ForeColor="red"
ErrorMessage="please
select date" Display="dynamic" Text="*" ValidationGroup="Submit" ControlToValidate="txtdob" runat="server" />
</td>
</tr>
<tr>
<td>Gender :</td>
<td>
<asp:RadioButtonList runat="server"
ID="rblgender"
RepeatDirection="Horizontal">
<asp:ListItem Text="Male" Value="0" />
<asp:ListItem Text="Female"
Value="1"
/>
</asp:RadioButtonList>
<asp:RequiredFieldValidator
ID="RequiredFieldValidator3"
ForeColor="Red"
ErrorMessage="Please
Select Gender" Display="Dynamic" Text="*" ValidationGroup="Submit" ControlToValidate="rblgender" runat="server" />
</td>
</tr>
<tr>
<td>Email :</td>
<td>
<asp:TextBox runat="server"
ID="txtemail"
/>
<asp:RequiredFieldValidator
ID="RequiredFieldValidator4"
ForeColor="Red"
ErrorMessage="Please Enter EmailId" Display="Dynamic"
Text="*"
ValidationGroup="Submit"
ControlToValidate="txtemail"
runat="server"
/>
<asp:RegularExpressionValidator
ID="txtEmailIDRegularExpression"
runat="server"
ErrorMessage="
Please Enter a Valid Email Address."
ControlToValidate="txtemail"
ValidationGroup="Submit"
ValidationExpression="^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"
Display="Dynamic" SetFocusOnError="true" Text="*" ForeColor="Red"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td>Country :</td>
<td>
<asp:DropDownList ID="ddlcountry"
runat="server">
<asp:ListItem Text="Select
Country" Value="0" />
<asp:ListItem Text="India"
Value="1"
/>
<asp:ListItem Text="USA" Value="2" />
<asp:ListItem Text="Japan"
Value="3"
/>
<asp:ListItem Text="China"
Value="4"
/>
</asp:DropDownList>
<asp:RequiredFieldValidator
ID="RequiredFieldValidator5"
ForeColor="Red"
ErrorMessage="Please
Select Country" Display="Dynamic" Text="*" ValidationGroup="Submit" InitialValue="0" ControlToValidate="ddlcountry" runat="server" />
</td>
</tr>
<tr>
<td>City :</td>
<td>
<asp:DropDownList ID="ddlcity"
runat="server">
<asp:ListItem Text="Select City"
Value="0"
/>
<asp:ListItem Text="Ahmedabad"
Value="1"
/>
<asp:ListItem Text="Rajkot"
Value="2"
/>
<asp:ListItem Text="Bhavanagar"
Value="3"
/>
<asp:ListItem Text="Surat"
Value="4"
/>
<asp:ListItem Text="Vadodara"
Value="4"
/>
</asp:DropDownList>
<asp:RequiredFieldValidator
ID="RequiredFieldValidator6"
ForeColor="Red"
ErrorMessage="Please
Select City" Display="Dynamic" Text="*" ValidationGroup="Submit" InitialValue="0" ControlToValidate="ddlcity" runat="server" />
</td>
</tr>
<tr>
<td>Photo :
</td>
<td>
<asp:FileUpload runat="server"
ID="fileupload1"
/>
<asp:RequiredFieldValidator
ID="RequiredFieldValidator7"
ErrorMessage="Please
Select Image" Display="Dynamic" Text="*" ForeColor="Red" ValidationGroup="Submit" ControlToValidate="fileupload1" runat="server" />
<asp:RegularExpressionValidator
ID="RegularExpressionValidator1"
ValidationExpression="([a-zA-Z0-9\s_\\.\-:])+(.jpg|.png|.gif)$"
ControlToValidate="fileupload1" runat="server" ForeColor="Red" ErrorMessage="Please select Only Jpg,Png And Gif Image"
Display="Dynamic"
ValidationGroup="Submit"
Text="*"
/>
</td>
</tr>
<tr>
<td>
<asp:Button Text="Submit"
OnClick="btnsubmit_Click"
ID="btnsubmit" runat="server" ValidationGroup="Submit" />
<asp:Button Text="Cancel"
ID="Btncancel"
OnClick="Btncancel_Click"
runat="server"
/>
</td>
</tr>
</table>
<asp:ValidationSummary ID="ValidationSummary1" runat="server"
ShowMessageBox="true"
ShowSummary="false"
ValidationGroup="Submit"
/>
</div>
</fieldset>
</div>
<div>
<asp:GridView ID="gvAll" runat="server"
AutoGenerateColumns="false" DataKeyNames="EmpId" PageSize="10" EmptyDataText="No Record Found..">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkAll" runat="server"
onclick="checkAll(this);"
/>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chk" runat="server"
onclick="Check_Click(this)"
/>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="EmpId" HeaderText="Sr No." />
<asp:BoundField DataField="EmpName" HeaderText="Name" />
<asp:BoundField DataField="DOB" HeaderText="Date Of Birth" DataFormatString="{0:d}" />
<asp:BoundField DataField="Email" HeaderText="Email Id" />
<asp:BoundField DataField="Country" HeaderText="Country" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:TemplateField HeaderText="Photo">
<ItemTemplate>
<asp:Image ID="Image1" ImageUrl='<%#Eval("Photo") %>' runat="server"
Height="50px"
Width="50px"
/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnDelete" runat="server" Text="Delete"
OnClientClick="return ConfirmDelete();" OnClick="btnDelete_Click"
/>
<cc1:ConfirmButtonExtender ID="ConfirmButtonExtender1" runat="server"
TargetControlID="btnDelete"
ConfirmText="Are you sure you want to delete this item?"
Enabled="true">
</cc1:ConfirmButtonExtender>
</div>
</form>
</body>
</html>
Registration.aspx.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.IO;
public partial class Registration : System.Web.UI.Page
{
SqlConnection
con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyCon"].ConnectionString);
protected void Page_Load(object
sender, EventArgs e)
{
try
{
if
(!IsPostBack)
BindGrid();
}
catch (Exception ex)
{
throw
ex;
}
}
private void BindGrid()
{
SqlDataAdapter
sda = new SqlDataAdapter("select * from Shyam_PracticalDemo",
con);
DataTable
dt = new DataTable();
sda.Fill(dt);
if (dt
!= null)
{
gvAll.DataSource = dt;
gvAll.DataBind();
}
}
protected void btnDelete_Click(object
sender, EventArgs e)
{
int
count = 0;
GetData();
ArrayList
arr = (ArrayList)ViewState["SelectedRecords"];
count = arr.Count;
for (int i = 0; i < gvAll.Rows.Count; i++)
{
if
(arr.Contains(gvAll.DataKeys[i].Value))
{
DeleteRecord(gvAll.DataKeys[i].Value.ToString());
arr.Remove(gvAll.DataKeys[i].Value);
}
}
ViewState["SelectedRecords"]
= arr;
BindGrid();
}
private void DeleteRecord(string
EmpId)
{
SqlDataAdapter
da = new SqlDataAdapter("select * from Shyam_PracticalDemo where
EmpId='"+EmpId+"'",
con);
DataTable
dt = new DataTable();
da.Fill(dt);
if
(dt.Rows[0]["Photo"] != null)
{
string
FileName = dt.Rows[0]["Photo"].ToString();
string
FilePath = Server.MapPath(FileName);
File.Delete(FilePath);
}
SqlCommand
cmd = new SqlCommand("delete from Shyam_PracticalDemo where
EmpId=@EmpId", con);
cmd.Parameters.AddWithValue("@EmpId", EmpId);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
private void GetData()
{
ArrayList
arr = new ArrayList();
if
(ViewState["SelectedRecords"] != null)
arr = (ArrayList)ViewState["SelectedRecords"];
CheckBox
chkAll = (CheckBox)gvAll.HeaderRow.Cells[0].FindControl("chkAll");
for (int i = 0; i < gvAll.Rows.Count; i++)
{
if
(chkAll.Checked)
{
if
(!arr.Contains(gvAll.DataKeys[i].Value))
{
arr.Add(gvAll.DataKeys[i].Value);
}
}
else
{
CheckBox
chk = (CheckBox)gvAll.Rows[i].Cells[0].FindControl("chk");
if
(chk.Checked)
{
if
(!arr.Contains(gvAll.DataKeys[i].Value))
{
arr.Add(gvAll.DataKeys[i].Value);
}
}
else
{
if
(arr.Contains(gvAll.DataKeys[i].Value))
{
arr.Remove(gvAll.DataKeys[i].Value);
}
}
}
}
ViewState["SelectedRecords"]
= arr;
}
protected void btnsubmit_Click(object
sender, EventArgs e)
{
try
{
//SqlDataAdapter
da = new SqlDataAdapter("select * from
Shyam_PracticalDemo where Email='" + txtemail.Text + "'",
con);
//DataTable
dt = new DataTable();
//da.Fill(dt);
//if
(dt.Rows[0]== null)
//{
string
FileNamePath = "";
if
(fileupload1.HasFile)
{
FileNamePath = "~/Image/" + fileupload1.FileName;
string
FilePath = Server.MapPath("~/" + "Image" + "/"
+ fileupload1.FileName);
fileupload1.SaveAs(FilePath);
}
con.Open();
SqlCommand
cmd = new SqlCommand("insert into
Shyam_PracticalDemo(EmpName,DOB,Gender,Email,Country,City,Photo)values(@EmpName,@DOB,@Gender,@Email,@Country,@City,@Photo)",
con);
cmd.Parameters.AddWithValue("@EmpName", txtname.Text);
cmd.Parameters.AddWithValue("@DOB", txtdob.Text);
cmd.Parameters.AddWithValue("@Gender", rblgender.SelectedItem.Text);
cmd.Parameters.AddWithValue("@Email", txtemail.Text);
cmd.Parameters.AddWithValue("@Country",
ddlcountry.SelectedItem.Text);
cmd.Parameters.AddWithValue("@City", ddlcity.SelectedItem.Text);
cmd.Parameters.AddWithValue("@Photo", FileNamePath);
cmd.ExecuteNonQuery();
BindGrid();
ClearControl();
con.Close();
//}
//else
//{
//
ClientScript.RegisterStartupScript(this.GetType(), "myalert",
"alert('This Email Already Exists');", true);
//}
}
catch (Exception ex)
{
throw
ex;
}
}
protected void Btncancel_Click(object
sender, EventArgs e)
{
try
{
ClearControl();
}
catch (Exception ex)
{
throw
ex;
}
}
private void ClearControl()
{
txtname.Text = string.Empty;
txtdob.Text = string.Empty;
txtemail.Text = string.Empty;
ddlcountry.ClearSelection();
ddlcity.ClearSelection();
rblgender.ClearSelection();
}
}
0 comments:
Post a Comment