User login

Add a Select All CheckBox to Table with CheckBoxes

If you have a GridView with multiple selection checkboxes you may want to add a 'Select All' checkbox in the header row to select or clear all checkboxes at once.
To accomplish this, you could use the following technique. First, add the following statement your asp code:

<asp:TemplateField HeaderText="Select">
<HeaderTemplate>
<asp:CheckBox runat="server" ID="cbAll" onclick="selectAllCheckboxes(this);"/>
</HeaderTemplate>
....
</asp:TemplateField>

Clicking this checkbox in the browser will call a JavaScript function that we are going to write now. The function receives a reference to the checkbox element as a parameter.

function selectAllCheckboxes(elem){
//first we obtain the current checked state of the 'Select All' checkbox. It could be true or false.
var state = elem.checked;
//next, we obtain a reference to the table element by calling a getParent function.
var tbl = getParent(elem, "TABLE");
//get an array of all checkboxes in the table
var chks = tbl.getElementsByTagName("INPUT");
var len = chks.length;
//loop through the array of checkbox elements
//assign a checked value to each
for(var i=0; i< len; i++){
if(chks[i].type=='checkbox') {
chks[i].checked =state;
}
}
}

A listing of the getParent function is located here