Check Uncheck all CheckBoxes in an ASP.NET GridView using jQuery

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

image

The entire source code can be downloaded over here






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

14 comments:

Anonymous said...

Does it handle few GridViews on one page and GridViews inside UpdatePanel?

Greetz

Suprotim Agarwal said...

If you want to create a generic code for all GridView's, then you will have to use a selector for a class rather than an id.

For eg: $("#GridView1 ..) will become $(".GridViewClass ...") where GridViewClass is the class applied to all GridView's you want to select. The same is for the CheckBox selection too.

Anonymous said...

thanks :) So I will download the code (thx for that!) and test it a little bit.

Greetz

Anonymous said...

If there is more than one checkbox in a row[for other requirement] the above code will check it as well..
You need to rewrite the selection to access the checkbox that belongs a particular child TD...

FP said...

I did something like this recently and used this in the template field:

<input type="checkbox" id="selectAllCB" onclick="selectAllCheckboxes('grid', this.checked)" />

and the JS (cssClass is the class of the grid view):

function selectAllCheckboxes(cssClass, select)
{
$("." + cssClass + " input[type='checkbox']").attr("checked", select);
}

Just a slightly different way of doing it. Would also work for multiple grid views (just use a different css class)

Anonymous said...

if gridview in update panel it can not work can u provide me a solution

Anonymous said...

in Update panle not work

Unknown said...

I've tried this, but it doesn't seem to work because my GridView is in a UpdatePanel. Any ideas??

Suprotim Agarwal said...

I will work on the example to make it work with an UpdatePanel in a day or two.

Watch out for this space!

Unknown said...

Any update on having the js script work with UpdatePanel??

Suprotim Agarwal said...

I completely forgot about this post..my bad! I have posted the solution here


Check Uncheck all CheckBoxes in an ASP.NET GridView kept in an Update Panel using jQuery

Anonymous said...

can you provide code that will check the "checkAll" check box when all checkbox in the gridview are checked? for example, when you uncheck one of checkbox, the "checkall" is unchecked, if i re-check the one i unchecked, i want the "checkall" to be checked.

thanks.

Joshua Blackstone said...

It should be noted that this example may not work as it currently stands. I know for experienced developers this isnt an issue, but if you use this in a master page, if you have ASP.NET 4.0, change the gridview's clientid mode to Static. Previous versions would need to find the id in the source code, and change #GridView1 to something similar to #MainContent_GridView1, with MainContent being the ContentPlaceholderID. Good sample, thanks.

nareshreddy said...

Works like Charm!! Thanks alot...it was not working in IE when I placed Script in HEAD section. Then I moved code to BODY it is working fine. But it works fine in either way in Chrome.. THanks any ways!!