aspdotnet_website_programming thread: How to check all CheckBoxes in a DataGrid on the client side
I looked all over for a way to check all items and uncheck all items in an
ASP.NET DataGrid, and finally had to roll my own code. Thought I would
pass it along to anyone doing a web search.
First create a JavaScript file for your application, which includes the
following function:
FormFunctions.js
...
//checks all DataGrid CheckBoxes with the given name with the given
value
function CheckAllDataGridCheckBoxes(aspCheckBoxID, checkVal) {
re = new RegExp(':' + aspCheckBoxID + '$') //generated control
name starts with a colon
for(i = 0; i < document.forms[0].elements.length; i++) {
elm = document.forms[0].elements[i]
if (elm.type == 'checkbox') {
if (re.test(elm.name)) {
elm.checked = checkVal
}
}
}
}
...
The script takes the name of the DataGrid CheckBox to be checked and the
value to apply (checked or unchecked).
In your .aspx file, you need to include the JavaScript file as follows:
MyForm.aspx
...
<HTML>
<HEAD>
...
<script language="javascript"
src="/MyWebApp/MyUtils/FormFunctions.js"></script>
...
</HEAD>
...
Finally, add the CheckBox to your DataGrid, including a call to the script
in the onclick event.
MyForm.aspx
...
<Columns>
<asp:TemplateColumn>
<HeaderTemplate>
<input id="chkAllItems" type="checkbox"
onclick="CheckAllDataGridCheckBoxes('chkItemChecked', document.forms
[0].chkAllItems.checked)" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox id="chkItemChecked"
runat="server"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateColumn>
...
Notice that the call to the JavaScript function passes in the name of the
CheckBox appearing on each row and the value of the check all CheckBox.