Introduction:
In one of my articles I discussed how to select checkboxes inside the GridView control. You can view the article here. This is an extension to that article in which, I will discuss some additional features. These features include using regular expression to limit the checkbox selection on a particular GridView and de-selecting the parent checkbox when all child checkboxes are un-checked.
Creating the GridView Control:
The first task is to create a simple GridView control using template fields. I strongly recommend using template fields instead of bound fields for the following reasons.
1) Template fields allow embedding the ASP.NET controls.
2) You don’t have to reorganize the appearance of the GridView after a new template field is added. This is because template field do not depend on the index number like the bound fields.
3) Template fields allow access to ASP.NET controls even if the fields are not visible.
Finally, here is the code for the GridView control.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<input type="checkbox" id="chkAll" name="chkAll" onclick="Check(this)" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblCategoryName" runat="server" Text = '<%# Eval("CategoryName") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The HeaderTemplate contains the HTML checkbox and serves as the parent checkbox. The ItemTemplate contains the ASP.NET checkboxes.
Populating the GridView Control:
I have used DataSet to populate the GridView control but you can use any type of container object to complete the task.
private void BindData()
{
string connectionString = "Server=localhost;Database=Northwind;Trusted_Connection=true";
SqlConnection myConnection = new SqlConnection(connectionString);
SqlDataAdapter ad = new SqlDataAdapter("SELECT CategoryID, CategoryName FROM Categories", myConnection);
DataSet ds = new DataSet();
ad.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
Now, if you run the application you will see the GridView displayed on the page.

NOTE: I have added styles to make the GridView look pretty!
Selecting and Deselecting CheckBoxes:
At this point your GridView control is displayed on the page and we need to implement the functionality to select and deselect all the child checkboxes when the parent checkbox is checked.
If you take a look at the GridView HTML code you will notice that the parent checkbox (chkAll) fires the Check function when clicked. Let’s see the Check function implementation.
function Check(parentChk)
{
var elements = document.getElementsByTagName("INPUT");
for(i=0; i<elements.length;i++)
{
if(parentChk.checked == true)
{
if( IsCheckBox(elements[i]) && IsMatch(elements[i].id))
{
elements[i].checked = true;
}
}
&nbs