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
Member
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

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
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 
GeneralMy vote of 5memberchetan virkar25 May '12 - 21:57 
GeneralMy vote of 5memberbhaskarareddy4 May '12 - 1:35 
GeneralMy vote of 4memberdtsfi14 Mar '12 - 1:22 
GeneralMy vote of 2membercaliff2221 Jan '12 - 6:22 
GeneralThank You..nice ArticlememberPraveen kumar. Bhuvanagiri13 Jan '12 - 0:25 
QuestionError in select allmemberSoner Sari11 Jan '12 - 1:53 
GeneralThanks!memberyaroopig17 Nov '11 - 15:32 
GeneralMy vote of 5memberManu K.Jayadev25 May '11 - 23:38 
GeneralMy vote of 5membertheintoehan10 Mar '11 - 18:26 
GeneralMy vote of 5memberankurbhutani26 Feb '11 - 8:25 
GeneralMy vote of 5memberThrinath reddy25 Feb '11 - 0:28 
GeneralMy vote of 5memberjcrussell23 Feb '11 - 0:34 
GeneralSlight Changememberjcrussell23 Feb '11 - 0:32 
GeneralMy vote of 5membernoblevaibhav4 Feb '11 - 6:04 
GeneralMy vote of 5membersoul negi21 Sep '10 - 2:46 
GeneralPb with value rows.count()membergdoub12 Apr '10 - 3:38 
Generalwell donememberDonsw18 Apr '09 - 10:34 
GeneralRe: well donemvpSamir NIGAM14 Sep '09 - 1:35 
GeneralHelpful articlememberSanjay4India6 Apr '09 - 1:40 
GeneralRe: Helpful articlemvpSamir NIGAM14 Sep '09 - 1:36 
GeneralRe: Helpful articlemvpSamir NIGAM17 Sep '09 - 10:09 
QuestionNot working inside UpdatePanelmemberTamil Mannan9 Mar '09 - 20:12 
AnswerRe: Not working inside UpdatePanelmvpSamir NIGAM14 Sep '09 - 1:52 
Generalsimplified versionmemberJim Brooks24 Feb '09 - 10:44 
GeneralRe: simplified versionmvpSamir NIGAM14 Sep '09 - 1:55 
Generalissue with paging on postback with filtered recordsmembersvknair27 Jan '09 - 1:32 
GeneralRe: issue with paging on postback with filtered recordsmvpSamir NIGAM14 Sep '09 - 1:59 
Generalerror in using the selectall checkboxmembersvknair27 Jan '09 - 1:22 
GeneralRe: error in using the selectall checkboxmvpSamir NIGAM14 Sep '09 - 1:57 
GeneralPaging IssuememberCoolBreeze81230 May '08 - 4:10 
GeneralRe: Paging Issuemember SAMir Nigam 30 May '08 - 19:27 
GeneralRe: Paging IssuememberCoolBreeze81231 May '08 - 3:26 
GeneralError when datasource is emptymemberPetr Stejskal4 May '08 - 9:54 
GeneralRe: Error when datasource is emptymember Samir Nigam 6 May '08 - 19:46 
GeneralhimemberMohamad Kaifi2 May '08 - 18:23 
GeneralRe: himember Samir Nigam 2 May '08 - 18:29 
GeneralRe: himemberMohamad Kaifi2 May '08 - 18:32 
GeneralRe: himember Samir Nigam 2 May '08 - 23:51 
Questionhow to include javascript functions instead of placing in the aspx file?memberPetr Stejskal1 May '08 - 8:46 
AnswerRe: how to include javascript functions instead of placing in the aspx file? [modified]member Samir Nigam 1 May '08 - 19:17 
GeneralRe: how to include javascript functions instead of placing in the aspx file?membertfpayne7224 Nov '08 - 9:10 
GeneralRe: how to include javascript functions instead of placing in the aspx file?memberSameer NIGAM24 Nov '08 - 18:21 
Questionhow to create dropdownlist option in grid view controlmemberPragya Khatri24 Feb '08 - 19:07 
AnswerRe: how to create dropdownlist option in grid view controlmember SAMir Nigam 21 May '08 - 18:09 
Generalhighlight rowmemberTim Vandeweerd19 Feb '08 - 8:38 
GeneralRe: highlight rowmember Samir Nigam 19 Feb '08 - 16:42 
GeneralExcellent Job.....memberD. PAUL17 Feb '08 - 18:19 
GeneralRe: Excellent Job.....member SAMir Nigam 21 May '08 - 18:06 
GeneralPagingmemberMark Henke13 Feb '08 - 4:34 

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

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