Click here to Skip to main content
6,291,124 members and growing! (15,255 online)
Email Password   helpLost your password?
Web Development » ASP.NET Controls » Grid Controls     Intermediate License: The Code Project Open License (CPOL)

Selecting / Deselecting all the CheckBoxes Inside a GridView

By Samir NIGAM

This article describes how to select and unselect all the checkboxes inside a GridView control.
C# (C# 2.0), Javascript, CSS, HTML, .NET (.NET 2.0), ASP.NET, ADO.NET, Dev
Posted:27 Jan 2008
Updated:9 May 2008
Views:53,307
Bookmarked:53 times
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
32 votes for this article.
Popularity: 6.05 Rating: 4.02 out of 5
2 votes, 6.3%
1
1 vote, 3.1%
2
4 votes, 12.5%
3
1 vote, 3.1%
4
24 votes, 75.0%
5

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


Member
SAMIR NIGAM is a Senoir Software Engineer at STPL, Lucknow, INDIA.
He is a CodeProject MVP 2009, 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, results-driven IT
professional having 3+ years of hands-on experience in web-based solutions
in Microsoft Technologies using ASP.NET 2.0, C# 2.0, AJAX,
Microsoft Enterprise Library , MS SQL Server 2005. Currently he has possessed following degrees:

  • MCA from U.P. Technical University, Lucknow, INDIA.

  • PGDCA from Institute of Engineering and Rural Technology, Allahabad, INDIA.

  • BSc 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:

Contact: nigam.samir@hotmail.com

Occupation: Software Developer (Senior)
Company: STPL
Location: India India

Other popular ASP.NET Controls articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 48 (Total in Forum: 48) (Refresh)FirstPrevNext
Generalwell done PinmemberDonsw11:34 18 Apr '09  
GeneralHelpful article PinmemberSanjay4India2:40 6 Apr '09  
QuestionNot working inside UpdatePanel PinmemberTamil Mannan21:12 9 Mar '09  
Generalsimplified version PinmemberJim Brooks11:44 24 Feb '09  
Generalissue with paging on postback with filtered records Pinmembersvknair2:32 27 Jan '09  
Generalerror in using the selectall checkbox Pinmembersvknair2:22 27 Jan '09  
GeneralPaging Issue PinmemberCoolBreeze8125:10 30 May '08  
GeneralRe: Paging Issue Pinmember SAMir Nigam 20:27 30 May '08  
GeneralRe: Paging Issue PinmemberCoolBreeze8124:26 31 May '08  
GeneralError when datasource is empty PinmemberPetr Stejskal10:54 4 May '08  
GeneralRe: Error when datasource is empty Pinmember Samir Nigam 20:46 6 May '08  
Generalhi PinmemberMohamad Kaifi19:23 2 May '08  
GeneralRe: hi Pinmember Samir Nigam 19:29 2 May '08  
GeneralRe: hi PinmemberMohamad Kaifi19:32 2 May '08  
GeneralRe: hi Pinmember Samir Nigam 0:51 3 May '08  
Generalhow to include javascript functions instead of placing in the aspx file? PinmemberPetr Stejskal9:46 1 May '08  
GeneralRe: how to include javascript functions instead of placing in the aspx file? [modified] Pinmember Samir Nigam 20:17 1 May '08  
GeneralRe: how to include javascript functions instead of placing in the aspx file? Pinmembertfpayne7210:10 24 Nov '08  
GeneralRe: how to include javascript functions instead of placing in the aspx file? PinmemberSameer NIGAM19:21 24 Nov '08  
Questionhow to create dropdownlist option in grid view control PinmemberPragya Khatri20:07 24 Feb '08  
AnswerRe: how to create dropdownlist option in grid view control Pinmember SAMir Nigam 19:09 21 May '08  
Generalhighlight row PinmemberTim Vandeweerd9:38 19 Feb '08  
GeneralRe: highlight row Pinmember Samir Nigam 17:42 19 Feb '08  
GeneralExcellent Job..... PinmemberD. PAUL19:19 17 Feb '08  
GeneralRe: Excellent Job..... Pinmember SAMir Nigam 19:06 21 May '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 9 May 2008
Editor: Smitha Vijayan
Copyright 2008 by Samir NIGAM
Everything else Copyright © CodeProject, 1999-2009
Web15 | Advertise on the Code Project