Click here to Skip to main content
Click here to Skip to main content

Selecting / Deselecting all the CheckBoxes Inside a GridView

By , 9 May 2008
 

Preview.gif

Introduction

I am going to present here a functionality that selects / deselects all checkboxes of a particular column inside a GridView control, provided the header checkbox of that column is checked or unchecked using JavaScript. This functionality also has a feature that when all checkboxes of a particular column inside the GridView are checked, then the header checkbox gets checked, and vice versa.

Using the code

I have used a TemplateField inside the GridView and put a CheckBox in the ItemTemplate as well as another CheckBox in the HeaderTemplate of the TemplateField.

The HTML code looks like this:

<asp:GridView ID="gvCheckboxes" runat="server" 
              AutoGenerateColumns="False" OnRowCreated="gvCheckboxes_RowCreated">
   <Columns>
      <asp:BoundField HeaderText="S.N." DataField="sno">
         <HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="50px" />
         <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="50px" />
      </asp:BoundField>
      <asp:TemplateField HeaderText="Select">
         <ItemTemplate>
            <asp:CheckBox ID="chkBxSelect" runat="server" />
         </ItemTemplate>
         <HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="50px" />
         <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="50px" />
         <HeaderTemplate>
            <asp:CheckBox ID="chkBxHeader" 
                 onclick="javascript:HeaderClick(this);" runat="server" />
         </HeaderTemplate>
      </asp:TemplateField>
      <asp:TemplateField>
         <ItemTemplate>
            <asp:CheckBox ID="chkBx" runat="server" />
         </ItemTemplate>
         <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="50px" />
      </asp:TemplateField>
   </Columns>
   <RowStyle BackColor="Moccasin" />
   <AlternatingRowStyle BackColor="NavajoWhite" />
   <HeaderStyle BackColor="DarkOrange" Font-Bold="true" ForeColor="white" />
</asp:GridView>

Attach a client-side onclick event on the header checkbox [chkBxHeader].

<asp:CheckBox ID="chkBxHeader" onclick="javascript:HeaderClick(this);" runat="server" /> 

Put the following code in the GridView's RowCreated event:

if (e.Row.RowType == DataControlRowType.DataRow && 
   (e.Row.RowState == DataControlRowState.Normal ||
    e.Row.RowState == DataControlRowState.Alternate))
{
   CheckBox chkBxSelect = (CheckBox)e.Row.Cells[1].FindControl("chkBxSelect");
   CheckBox chkBxHeader = (CheckBox)this.gvCheckboxes.HeaderRow.FindControl("chkBxHeader");
   chkBxSelect.Attributes["onclick"] = string.Format
                                          (
                                             "javascript:ChildClick(this,'{0}');",
                                             chkBxHeader.ClientID
                                          );
}

In the above code, a client side onclick event has been attached to the child checkbox [chkBxChild].

Add this JavaScript in the page’s head section:

<script type="text/javascript">
var TotalChkBx;
var Counter;

window.onload = function()
{
   //Get total no. of CheckBoxes in side the GridView.
   TotalChkBx = parseInt('<%= this.gvCheckboxes.Rows.Count %>');

   //Get total no. of checked CheckBoxes in side the GridView.
   Counter = 0;
}

function HeaderClick(CheckBox)
{
   //Get target base & child control.
   var TargetBaseControl = 
       document.getElementById('<%= this.gvCheckboxes.ClientID %>');
   var TargetChildControl = "chkBxSelect";

   //Get all the control of the type INPUT in the base control.
   var Inputs = TargetBaseControl.getElementsByTagName("input");

   //Checked/Unchecked all the checkBoxes in side the GridView.
   for(var n = 0; n < Inputs.length; ++n)
      if(Inputs[n].type == 'checkbox' && 
                Inputs[n].id.indexOf(TargetChildControl,0) >= 0)
         Inputs[n].checked = CheckBox.checked;

   //Reset Counter
   Counter = CheckBox.checked ? TotalChkBx : 0;
}

function ChildClick(CheckBox, HCheckBox)
{
   //get target control.
   var HeaderCheckBox = document.getElementById(HCheckBox);

   //Modifiy Counter; 
   if(CheckBox.checked && Counter < TotalChkBx)
      Counter++;
   else if(Counter > 0) 
      Counter--;

   //Change state of the header CheckBox.
   if(Counter < TotalChkBx)
      HeaderCheckBox.checked = false;
   else if(Counter == TotalChkBx)
      HeaderCheckBox.checked = true;
}
</script>

In the above script, there are two global variables: TotalChkBx and Counter. These are initialised in the window.onload event. There are two methods: HeaderClick and ChildClick. The method HeaderClick checks / unchecks all checkboxes of a particular column inside the GridView depending upon whether the header checkbox is checked or unchecked. The method ChildClick checks / unchecks the header checkbox depending upon whether all checkboxes of a particular column inside the GridView are checked or unchecked.

Just download the sample application and enjoy coding! I hope you will like this article.

Supported browsers

I have tested this script on the following browsers:

Browsers.png

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Samir NIGAM
Team Leader
India India
SAMIR NIGAM is a CodeProject MVP, a Microsoft Certified Technology
Specialist (MCTS)
as well as a Microsoft Certified Professional Developer (MCPD)
in C# for web-based applications. He is an insightful IT professional with
results-driven comprehensive technical skill having rich, hands-on work experience
in web-based applications using ASP.NET, C#, AJAX, Microsoft
Enterprise Library
, MS SQL Server 2005.
He has earned his master degree (MCA) from U.P. Technical University, Lucknow,
INDIA, his post graduate dipoma (PGDCA ) from Institute of Engineering and
Rural Technology, Allahabad, INDIA and his bachelor degree (BSc - Mathematics)
from University of Allahabad, Allahabad, INDIA.
He has good knowledge of Object Oriented Programming, 3-Tier Architecture
and Algorithm Analysis & Design as well as good command over cross-browser
client side programming using JavaScript.
Awards:


Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberrobzz212-Sep-12 22:02 
Its great and simple
GeneralMy vote of 5memberchetan virkar25-May-12 21:57 
solved my problem
good work !!!!!
GeneralMy vote of 5memberbhaskarareddy4-May-12 1:35 
Brief and easy solution for check box in gridview
GeneralMy vote of 4memberdtsfi14-Mar-12 1:22 
its simple and really flexible artical for checkbox with grid view thank you sir
 
i am varun kuarm my email id is varun.dtsfi@gmail.com
GeneralMy vote of 2membercaliff2221-Jan-12 6:22 
too much code for 'hello world' kind of task.
GeneralThank You..nice ArticlememberPraveen kumar. Bhuvanagiri13-Jan-12 0:25 
Almost it is working fine except 1 scenario.
That is When i opened popup,then if i do checked the remaining check boxes (which were not checked)that select all is not working in first time.From Second time it is working.
 
Thank you
QuestionError in select allmemberSoner Sari11-Jan-12 1:53 
when i used
TotalChkBx = parseInt('<%= this.GridView1.Rows.Count %>');
i took
The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
if i write
TotalChkBx = parseInt(this.GridView1.Rows.Count);
then select methods doesn't work ...
 
Thanks...
GeneralThanks!memberyaroopig17-Nov-11 15:32 
This works perfectly! Thank you.
GeneralMy vote of 5memberManu K.Jayadev25-May-11 23:38 
it really worked fine!!! nice article
GeneralMy vote of 5membertheintoehan10-Mar-11 18:26 
good performance
GeneralMy vote of 5memberankurbhutani26-Feb-11 8:25 
frst seen the code...than tried...
than commented the best...
GeneralMy vote of 5memberThrinath reddy25-Feb-11 0:28 
most helfful
GeneralMy vote of 5memberjcrussell23-Feb-11 0:34 
Great code and helped me save a bunch of time
GeneralSlight Changememberjcrussell23-Feb-11 0:32 
i changed the ChildClick method so that i don't have to use the Row Created method
 
I changed from
function ChildClick(CheckBox, HCheckBox)
{
   //get target control.
   var HeaderCheckBox = document.getElementById(HCheckBox);
 
 
to
 
   function ChildClick(CheckBox) {
            //get target control.
            var HeaderCheckBox = document.getElementById('<%= ((CheckBox)this.gvCheckboxes.HeaderRow.FindControl("chkBxHeader")).ClientID %>');
 

but this code is awesome. Thanks for posting!
Jason

GeneralMy vote of 5membernoblevaibhav4-Feb-11 6:04 
Brilliantly written and demonstrated...! Thanks a lot Smile | :)
GeneralMy vote of 5membersoul negi21-Sep-10 2:46 
It solves my problem.
GeneralPb with value rows.count()membergdoub12-Apr-10 3:38 
Hello, i just have a problem with ajax and your code, the variable TotalChkBx is always =0, so i can check all the children's checkbbox but not the head checkbox when all the children are checked.
 
Any idea ?
Generalwell donememberDonsw18-Apr-09 10:34 
I like what you did, I will have to try this on one of mine, I did the same but with check/uncheck all buttons,
 
cheers,
Donsw
My Recent Article : Ajax Calendar Control

GeneralRe: well donemvpSamir NIGAM14-Sep-09 1:35 
Thanks a lot.
 
Samir NIGAM
My Articles

GeneralHelpful articlememberSanjay4India6-Apr-09 1:40 
Its really genuine article that saved my lot of time. Can you implement this idea for dataGridView in windows application? If possible post a new article on that. Smile | :)
 
S#

GeneralRe: Helpful articlemvpSamir NIGAM14-Sep-09 1:36 
Thanks a lot. Yes. It is almost ready. plz wait for week.
 
Samir NIGAM
My Articles

GeneralRe: Helpful articlemvpSamir NIGAM17-Sep-09 10:09 
hi,
now i've posted the same for windows forms. plz have a look -
Toggling states of all CheckBoxes Inside a DataGridView column
 
Samir NIGAM
My Articles

QuestionNot working inside UpdatePanelmemberTamil Mannan9-Mar-09 20:12 
Hi,
 
Thnx for nice article.
 
It was working fine. Once I added the updatePanel in my page. It is not working perfectly and also not even giving any error messages.
 
any idea how make work the same function in updatepanel. Frown | :(
 
Tamil

AnswerRe: Not working inside UpdatePanelmvpSamir NIGAM14-Sep-09 1:52 
Thanks a lot.
 
use following code -
 
window.onload = function()
 {
     Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
 }
 
 function BeginRequestHandler(sender, args)
 {
           //Get total no. of CheckBoxes in side the GridView.
   TotalChkBx = parseInt('<%= this.gvCheckboxes.Rows.Count %>');
 
   //Get total no. of checked CheckBoxes in side the GridView.
   Counter = 0;
 }
hope this works for u.
 
Samir NIGAM
My Articles

Generalsimplified versionmemberJim Brooks24-Feb-09 10:44 
I did a simplified version on my blog:
 
http://blog.digitaltools.com/post/2009/02/11/Checking-All-CheckBoxes-in-a-GridView-Using-Client-Side-Script.aspx
 
Jim

GeneralRe: simplified versionmvpSamir NIGAM14-Sep-09 1:55 
Hi Jim. Another approach. But it is one way.
 
Samir NIGAM
My Articles

Generalissue with paging on postback with filtered recordsmembersvknair27-Jan-09 1:32 
paging ie first next last prev works fine when the whole dataset is populated in gridview
 
but if i filter out some records and populate the gridview . on load i get the things fine. suppose it show 5 pages on recod filteration.
but on postback ie on clciking next the whole dataset gets populated instead of only 5 pages
 
how do i rectify it
GeneralRe: issue with paging on postback with filtered recordsmvpSamir NIGAM14-Sep-09 1:59 
u have to filter next 5 records from the whole datasource.
 
Samir NIGAM
My Articles

Generalerror in using the selectall checkboxmembersvknair27-Jan-09 1:22 
i used the given code
but getting error in
TotalChkBx = parseInt("%=this.Gridview1.Rows.Count %"');
 
"this not declared"
 
i used tried removing this
i am using vb.net as code behind
GeneralRe: error in using the selectall checkboxmvpSamir NIGAM14-Sep-09 1:57 
use parseInt('<%= this.gvCheckboxes.Rows.Count %>');
 
Samir NIGAM
My Articles

GeneralPaging IssuememberCoolBreeze81230-May-08 4:10 
First off thank you for providing this solution. I have seen many attempts at providing this functionality and yours is one of the best.
 
I have it working with my GridView just fine; however, because I have paging on the GridView when I go to another page none of the checkboxes on the next page are checked.
 
Can you provide an example or show how to have the checkboxes on additional pages all checked, when the checkall checkbox is checked?
GeneralRe: Paging Issuemember SAMir Nigam 30-May-08 19:27 
Hi CoolBreeze812. Thanx for giving complements to my attempt. Actually whenever you move from one page to another, page postbacks & GridView has been re binded. Hence all the information gets lost. Also when you go to the next page, maintaining previous page's CheckBox state is irreleavent.
 
Now as for as your second question is concerned, put an hidden field on the page & store the state of the header CheckBox as:
 
document.getElementById('<%= this.hdnField.ClientID %>').value = CheckBox.checked;
 
Where hdnField is the id of the hidden field. Put the following code inthe RowCreated event of thr GridView:
 
if (e.Row.RowType == DataControlRowType.Header)
{
CheckBox chkBxSelect = (CheckBox)e.Row.Cells[1].FindControl ("chkBxHeader");
 
chkBxHeader.Checked = Convert.ToBoolean(hdnField.Value);
}

 
if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate))
{
chkBxSelect.Checked = Convert.ToBoolean(hdnField.Value);
}

 
I hove this will solve your problem. But in opinion this is also irreleavent.
 
SAMir Nigam

GeneralRe: Paging IssuememberCoolBreeze81231-May-08 3:26 
Thanks for the snippet SAMir, I will try this out.
 
I'm curious as to why you feel maintaing the state of all pages of checkboxes is irreleavent. Wouldn't that be the purpose of having a CheckAll checkbox to actually check all checkboxes of a particular column for all pages?
 
Please explain why you feel it is irreleavant to check all checkboxes of subsequent pages?
GeneralError when datasource is emptymemberPetr Stejskal4-May-08 9:54 
fix:
 
function ChildClick(CheckBox)
{
var Header = document.getElementById('<%= this.GridView1.HeaderRow %>');
if (Header == '')
return;
GeneralRe: Error when datasource is emptymember Samir Nigam 6-May-08 19:46 
Thanks Petr Stejskal. I've modified the code. Please check it.
 
SAMir Nigam

GeneralhimemberMohamad Kaifi2-May-08 18:23 
hi samir sir, this is kaifi working as software developer in OMNI-NET,Lucknow. i liked ur article of selecting checkboxes of gridview.can i get ur personel email id to get in touch with u thank you.
Mohd. Kaifi
mohamadkaifi@gmail.com
GeneralRe: himember Samir Nigam 2-May-08 18:29 
nigam.samir@hotmail.com
 
SAMir Nigam

GeneralRe: himemberMohamad Kaifi2-May-08 18:32 
thank you samir sir.u will be online on this id?
GeneralRe: himember Samir Nigam 2-May-08 23:51 
Hi Kaifi! Please call me from your email id. Use this forum only for this article related problems. please do not mind.
 
SAMir Nigam

Questionhow to include javascript functions instead of placing in the aspx file?memberPetr Stejskal1-May-08 8:46 
I want to include the javascript function like:
 
<script language="JavaScript" src="JScript.js">
</script>
 

but I'm getting error
Could anybody help me?
thanks
AnswerRe: how to include javascript functions instead of placing in the aspx file? [modified]member Samir Nigam 1-May-08 19:17 
Hi Petr Stejskal! this happend because u can not access following lines of code in the external JavaScript :
 
var TotalChkBx = parseInt('<%= this.gvCheckboxes.Rows.Count %>');
 
var TargetBaseControl = document.getElementById('<%= this.gvCheckboxes.ClientID %>');
 
var HeaderCheckBox
= document.getElementById('<%= this.gvCheckboxes.HeaderRow.FindControl("chkBxHeader").ClientID %>');

 
Code block '<%= %>' can only be accessed within the aspx page.
 
To use external JavaScript u have to put these lines of code into the window.onload event & take above variables as global. put rest of the code in the external JavaScript.
 
SAMir Nigam
modified on Friday, May 2, 2008 1:26 AM

GeneralRe: how to include javascript functions instead of placing in the aspx file?membertfpayne7224-Nov-08 9:10 
I put these lines in the onload event, but the variables are still null. Can you stil use the code block '<%= %>' in the window.onload event?
 
thanks.
GeneralRe: how to include javascript functions instead of placing in the aspx file?memberSameer NIGAM24-Nov-08 18:21 
hi tfpayne72. Actually with code block '<%= %>' you can get easily reference or other information about the server side control. e.g. if you put a textbox inside a gridview, then its generated id at client side is
 
something like gvCheckboxes_ctl02_chkBxSelect. but you can easily get this by using document.getElementById('<%= this.gvCheckboxes.ClientID %>');
 
i've put this line of code in the window.onload as here it is Guarantee that gridview is completely rendered. if not then this block will give null;
 
Samir NIGAM
My Articles

Questionhow to create dropdownlist option in grid view controlmemberPragya Khatri24-Feb-08 19:07 
I want to Create a dropdown list in the grid view and retreive the particular field according to the value selected.
 
Also ,
 
How can I Insert the data in grid view control
AnswerRe: how to create dropdownlist option in grid view controlmember SAMir Nigam 21-May-08 18:09 
Is this question is related to this article? plz ask questions, give suggestions & report bug related to this article only. yet simply take an ItemTemplate inside the GridView & drag & drop a DropDownList inside this ItemTemplate. After that u can bind it through suitable method.
 
SAMir Nigam

Generalhighlight rowmemberTim Vandeweerd19-Feb-08 8:38 
Hi, this has alternate row colors which I like. How about setting the background color to a 3rd color on check and resetting it to the proper row color or alternate row color which depends on which row was checked the row is unchecked?
 
Thanks, Tim
GeneralRe: highlight rowmember Samir Nigam 19-Feb-08 16:42 
Hi Tim! Please read this article: Hotmail-like Mouse Over & Mouse Out Effects on GridView. I'm sure you will find help from this article. If not please let me know.
 
SAMir Nigam

GeneralExcellent Job.....memberD. PAUL17-Feb-08 18:19 
it is extremely helpful.......
GeneralRe: Excellent Job.....member SAMir Nigam 21-May-08 18:06 
Thanx.
 
SAMir Nigam

GeneralPagingmemberMark Henke13-Feb-08 4:34 
Hey thx man this is the cleanest offering I have seem for this functionality!\
 
Just wondering if you can take it a step further and offer the same with Paging.
 
The problem is the state issue as I am sure you are aware?

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130617.1 | Last Updated 10 May 2008
Article Copyright 2008 by Samir NIGAM
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid