Click here to Skip to main content
15,867,453 members
Articles / Web Development / HTML
Article

Selecting / Deselecting all the CheckBoxes Inside a GridView

Rate me:
Please Sign up or sign in to vote.
4.64/5 (67 votes)
9 May 2008CPOL1 min read 386.5K   6.5K   105   76
This article describes how to select and unselect all the checkboxes inside a GridView control.

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.NET
<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.NET
<asp:CheckBox ID="chkBxHeader" onclick="javascript:HeaderClick(this);" runat="server" /> 

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

C#
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:

JavaScript
<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)


Written By
Technical Lead Infogain India Pvt Ltd
India India


Samir NIGAM is a Microsoft Certified Professional. He is an insightful IT professional with results-driven comprehensive technical skill having rich, hands-on work experience n web-based applications using ASP.NET, C#, AJAX, Web Service, WCF, jQuery, Microsoft Enterprise Library , LINQ, MS Entity Framework, nHibernate, MS SQL Server & SSRS.



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, n-Tier Architecture, SOLID Principle, and Algorithm Analysis & Design as well as good command over cross-browser client side programming using JavaScript & jQuery,.



Awards:



Comments and Discussions

 
GeneralRe: highlight row Pin
Samir NIGAM19-Feb-08 16:42
Samir NIGAM19-Feb-08 16:42 
GeneralExcellent Job..... Pin
D. PAUL17-Feb-08 18:19
D. PAUL17-Feb-08 18:19 
GeneralRe: Excellent Job..... Pin
Samir NIGAM21-May-08 18:06
Samir NIGAM21-May-08 18:06 
GeneralPaging Pin
Mark Henke13-Feb-08 4:34
Mark Henke13-Feb-08 4:34 
GeneralRe: Paging Pin
Samir NIGAM13-Feb-08 20:41
Samir NIGAM13-Feb-08 20:41 
GeneralRe: Paging Pin
Samir NIGAM13-Feb-08 21:54
Samir NIGAM13-Feb-08 21:54 
GeneralRe: Paging Pin
Mark Henke14-Feb-08 3:59
Mark Henke14-Feb-08 3:59 
GeneralRe: Paging Pin
Samir NIGAM14-Feb-08 17:00
Samir NIGAM14-Feb-08 17:00 
GeneralAdvanced Features When Selected CheckBoxes Inside the GridView Control Pin
azamsharp7-Feb-08 17:06
azamsharp7-Feb-08 17:06 
GeneralRe: Advanced Features When Selected CheckBoxes Inside the GridView Control Pin
Samir NIGAM7-Feb-08 21:24
Samir NIGAM7-Feb-08 21:24 
GeneralRe: Advanced Features When Selected CheckBoxes Inside the GridView Control Pin
Samir NIGAM13-Feb-08 19:48
Samir NIGAM13-Feb-08 19:48 
GeneralRe: Advanced Features When Selected CheckBoxes Inside the GridView Control Pin
azamsharp14-Feb-08 2:04
azamsharp14-Feb-08 2:04 
GeneralRe: Advanced Features When Selected CheckBoxes Inside the GridView Control Pin
Samir NIGAM14-Feb-08 3:20
Samir NIGAM14-Feb-08 3:20 
GeneralIts really helpful! Pin
Member 37906906-Feb-08 23:18
Member 37906906-Feb-08 23:18 
GeneralRe: Its really helpful! Pin
Samir NIGAM7-Feb-08 3:02
Samir NIGAM7-Feb-08 3:02 
GeneralThanks! Pin
wk6336-Feb-08 5:00
wk6336-Feb-08 5:00 
GeneralRe: Thanks! Pin
wk6336-Feb-08 8:50
wk6336-Feb-08 8:50 
GeneralRe: Thanks! Pin
Samir NIGAM6-Feb-08 16:57
Samir NIGAM6-Feb-08 16:57 
GeneralReally Help full...... Pin
fmlove29-Jan-08 22:35
fmlove29-Jan-08 22:35 
GeneralRe: Really Help full...... Pin
Samir NIGAM21-May-08 18:11
Samir NIGAM21-May-08 18:11 
GeneralNice Article Pin
Sandeep Shekhar28-Jan-08 18:55
Sandeep Shekhar28-Jan-08 18:55 
GeneralRe: Nice Article Pin
Samir NIGAM29-Jan-08 19:24
Samir NIGAM29-Jan-08 19:24 
QuestionDoes it works when GridView is inside UpdatePanel? Pin
binabic28-Jan-08 11:35
binabic28-Jan-08 11:35 
GeneralRe: Does it works when GridView is inside UpdatePanel? Pin
Samir NIGAM28-Jan-08 17:54
Samir NIGAM28-Jan-08 17:54 
Generalvery good article Pin
san_geit28-Jan-08 1:17
san_geit28-Jan-08 1:17 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.