Some time back I wrote articles about how to select checkboxes inside the GridView control.
1) Selecting CheckBoxes Inside the GridView Control
2) GridView Selection with a Twist
If you have not yet checked out the articles then please visit the links above.
Few days back a reader emailed me and asked that how he can restrict the selection of checkboxes when he has multiple GridView's on the page. In this post I am going to discuss the very same scenario.
First here is the gvCategories:
<h2>Categories</h2>
<asp:GridView ID="gvCategories" runat="server">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<input type="checkbox" onclick="toggleCheckBoxes('<%= gvCategories.ClientID %>',this.checked)" id="chkAll" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
As, you can see that the toggleCheckBoxes function takes the GridView ID as a parameter. This ensures that only the checkboxes residing inside that GridView are checked. Here is the toggleCheckBoxes function.
// toggle state of the checkbox between selected and not selected!
function toggleCheckBoxes(gvId, isChecked) {
var checkboxes = getCheckBoxesFrom(document.getElementById(gvId));
for (i = 0; i <= checkboxes.length - 1; i++) {
checkboxes[i].checked = isChecked;
}
}
The getCheckBoxesFrom function gets the checkboxes from the passed in control which in this case is the GridView control.
// get all the checkboxes from the container control
function getCheckBoxesFrom(gv) {
var checkboxesArray = new Array();
var inputElements = gv.getElementsByTagName("input");
if (inputElements.length == 0) null;
for (i = 0; i <= inputElements.length -1; i++) {
if (isCheckBox(inputElements[i])) {
checkboxesArray.push(inputElements[i]);
}
}
return checkboxesArray;
}
// checks if the elements is a checkbox or not
function isCheckBox(element)
{
return element.type == "checkbox";
}
A custom JavaScript Array is populated with the checkbox elements and returned to the client.
Now, you can include a second GridView on the page and you will notice that when you check mark the checkbox on one GridView it will NOT check mark the checkboxes in the second GridView.