Check All CheckBoxes In ASP.NET Gridview

Introduction
 
In this article we will see how to check and uncheck all CheckBoxes of an ASP.NET GridView control.
 
Background
 
There are times when we need to use a CheckBox control in an ASP.NET GridView for allowing selection of a particular row of the GridView. In some cases a GridView can contain 100s of records and if the user wants to select all rows of the GridView then selecting each row one by one is very tedious and a time-consuming job. To make it easier we will see how to write a simple method for selecting all CheckBoxes in a GridView. Take a look at the following snippets.
 
GridView Application 
 
Create a new Web Application using Visual Studio.
 
On the default.aspx page, place a GridView control with AutogeneratedColumn = false. The source for the GridView should look like below.
  1. <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">  
  2. <Columns>  
  3. <asp:TemplateField ShowHeader="false">  
  4. <ItemTemplate>  
  5. <asp:CheckBox ID="chkid" runat="server" />  
  6. </ItemTemplate>  
  7. </asp:TemplateField>  
  8. <asp:BoundField DataField="Auth_Name" HeaderText="Author Name" />  
  9. <asp:BoundField DataField="Auth_Loc" HeaderText="Location" />  
  10. </Columns>  
  11. </asp:GridView>  
Place two buttons on the WebForm; one for checking and the other for unchecking all checkboxes.
 
The CheckState method is for performing a check/uncheck operation in the GridView. This method will take true/false as input to check/uncheck the checkboxes of the GridView. As you can see from the below code, we look for CheckBox with ID chkId and check and uncheck it.
  1. private void CheckState(bool p)  
  2. {  
  3. foreach (GridViewRow row in GridView1.Rows)  
  4. {  
  5. CheckBox chkcheck = (CheckBox)row.FindControl("chkid");  
  6. chkcheck.Checked = p;  
  7. }  
  8. }  
Now, get data from a data source, bind your GridView and run it. You should be able to check or uncheck all check boxes by clicking a button.
 
Conclusion
 
By using a simple method we are able to check/uncheck 100 of rows also in GridView.
 
Here is a detailed article with data binding, Use CheckBoxes Inside ASP.NET GridView Control 
 
 


Similar Articles