I had recently written an article on Retrieve Rows Selected Using CheckBox in an ASP.NET GridView. A visitor Jeremy commented back with the following query:
“Can you also tell how to add a checkbox to the header so that i select/deselect all checkboxes. I do not want postbacks to occur when I perform this action.”
I immediately thought of doing this with jQuery. I had already written a similar script sometime back to Check/Uncheck all Items in an ASP.NET CheckBox List using jQuery. Using portions of that script, here’s how to Check UnCheck all CheckBoxes in an ASP.NET GridView using jQuery.
ASPX Page (with jQuery script)
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default4.aspx.cs"
Inherits="Default4" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Check Uncheck All Checkboxes In A GridView</title>
<script type='text/javascript'
src='http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js'></script>
<script type="text/javascript">
$(document).ready(function() {
var chkBox = $("input[id$='ChkAll']");
chkBox.click(
function() {
$("#GridView1 INPUT[type='checkbox']")
.attr('checked', chkBox
.is(':checked'));
});
// To deselect CheckAll when a GridView CheckBox
// is unchecked
$("#GridView1 INPUT[type='checkbox']").click(
function(e) {
if (!$(this)[0].checked) {
chkBox.attr("checked", false);
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
DataKeyNames="ID" >
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="ChkAll" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkSel" class="chkSel" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ID" HeaderText="EmployeeId"
SortExpression="EmployeeId" />
<asp:BoundField DataField="FName" HeaderText="FirstName"
SortExpression="FirstName" />
<asp:BoundField DataField="Age" HeaderText="Age"
SortExpression="Age" />
<asp:BoundField DataField="Sex" HeaderText="Sex"
SortExpression="Sex" />
</Columns>
</asp:GridView>
<br />
<asp:Button ID="btnRetrieveCheck" runat="server"
Text="Retrieve Checked Items" onclick="btnRetrieveCheck_Click" />
</div>
</form>
</body>
</html>
The jQuery code shown above finds all elements of the checkbox type inside the GridView and sets the ‘checked’ value of all items in it to true or false based on the checked value of the ‘ChkAll’ checkbox. The script also takes care of unchecking the ‘ChkAll’ checkbox, when one of the checkboxes in the GridView is unchecked. This part of the script was shared by Tim Hobbs.
C#
using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Default4 : System.Web.UI.Page
{
List<Employee> listEmp = new List<Employee>();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Employee emp = new Employee();
listEmp = emp.GetEmployees();
this.GridView1.DataSource = listEmp;
this.GridView1.DataBind();
}
}
protected void btnRetrieveCheck_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox cb = (CheckBox)row.FindControl("chkSel");
if (cb != null && cb.Checked)
{
Response.Write("Employee Id: " +
GridView1.DataKeys[row.RowIndex].Value
+ " Name: " + row.Cells[2].Text + "<br/>");
}
}
}
}
public class Employee
{
public int ID { get; set; }
public string FName { get; set; }
public int Age { get; set; }
public char Sex { get; set; }
public List<Employee> GetEmployees()
{
List<Employee> eList = new List<Employee>();
eList.Add(new Employee() { ID = 1, FName = "John", Age = 23, Sex = 'M' });
eList.Add(new Employee() { ID = 2, FName = "Mary", Age = 25, Sex = 'F' });
eList.Add(new Employee() { ID = 3, FName = "Amber", Age = 23, Sex = 'M' });
eList.Add(new Employee() { ID = 4, FName = "Kathy", Age = 25, Sex = 'M' });
eList.Add(new Employee() { ID = 5, FName = "Lena", Age = 27, Sex = 'F' });
eList.Add(new Employee() { ID = 6, FName = "John", Age = 28, Sex = 'M' });
eList.Add(new Employee() { ID = 7, FName = "Kathy", Age = 27, Sex = 'F' });
eList.Add(new Employee() { ID = 8, FName = "John", Age = 28, Sex = 'M' });
return eList;
}
}
VB.NET
Imports System
Imports System.Collections.Generic
Imports System.Web.UI
Imports System.Web.UI.WebControls
Partial Public Class Default4
Inherits System.Web.UI.Page
Private listEmp As New List(Of Employee)()
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If (Not Page.IsPostBack) Then
Dim emp As New Employee()
listEmp = emp.GetEmployees()
Me.GridView1.DataSource = listEmp
Me.GridView1.DataBind()
End If
End Sub
Protected Sub btnRetrieveCheck_Click(ByVal sender As Object, _
ByVal e As EventArgs)
For Each row As GridViewRow In GridView1.Rows
Dim cb As CheckBox = CType(row.FindControl("chkSel"), CheckBox)
If cb IsNot Nothing AndAlso cb.Checked Then
Response.Write("Employee Id: " & _
GridView1.DataKeys(row.RowIndex).Value & " Name: " & _
row.Cells(2).Text & "<br/>")
End If
Next row
End Sub
End Class
Public Class Employee
Private privateID As Integer
Public Property ID() As Integer
Get
Return privateID
End Get
Set(ByVal value As Integer)
privateID = value
End Set
End Property
Private privateFName As String
Public Property FName() As String
Get
Return privateFName
End Get
Set(ByVal value As String)
privateFName = value
End Set
End Property
Private privateAge As Integer
Public Property Age() As Integer
Get
Return privateAge
End Get
Set(ByVal value As Integer)
privateAge = value
End Set
End Property
Private privateSex As Char
Public Property Sex() As Char
Get
Return privateSex
End Get
Set(ByVal value As Char)
privateSex = value
End Set
End Property
Public Function GetEmployees() As List(Of Employee)
Dim eList As New List(Of Employee)()
eList.Add(New Employee() With {.ID = 1,.FName = "J",.Age = 23,.Sex = "M"c})
eList.Add(New Employee() With {.ID = 2,.FName = "M",.Age = 25,.Sex = "F"c})
eList.Add(New Employee() With {.ID = 3,.FName = "A",.Age = 23,.Sex = "M"c})
eList.Add(New Employee() With {.ID = 4,.FName = "K",.Age = 25,.Sex = "M"c})
eList.Add(New Employee() With {.ID = 5,.FName = "L",.Age = 27,.Sex = "F"c})
eList.Add(New Employee() With {.ID = 6,.FName = "J",.Age = 28,.Sex = "M"c})
eList.Add(New Employee() With {.ID = 7,.FName = "K",.Age = 27,.Sex = "F"c})
eList.Add(New Employee() With {.ID = 8,.FName = "J",.Age = 28,.Sex = "M"c})
Return eList
End Function
OUTPUT
The entire source code can be downloaded over here