Friday, March 14, 2008

Simultaneous Selection of Checkboxes in a GridView's column

If you are using checkboxes in GridView in order to select a few rows, then, no doubt, you have been faced with the task how to select/deselect all checkboxes in a selected column at a time. Usually it is solved by addition of special buttons somewhere or addition a checkbox in the GridView's column header.

I want to dwell on the second variant. In order to refrain from repetition of code all of required functionality can be hidden inside of a special control. This control is inherited from the CheckBox and have only one method overriden (OnLoad).
Inside the method a script is registered, this script allows to select/deselect all checkboxes in a GridView's column if a checkbox in the GridView's header is clicked. Besides, the script tracks situation when all checkboxes in rows are selected one by one and selects the checkbox in the column's header.
public class GridViewCheckBox : CheckBox
protected override void OnLoad(EventArgs e)
GridViewRow parentRow = this.NamingContainer as GridViewRow;

//checks whether the checkbox is inside of a template column (TemplateField)
if (parentRow != null)
//registers the script
string script = @"function gvCheckBoxClicked(sender,isHeader) {
var cell = sender.parentNode;
var rows = cell.parentNode.parentNode.rows;
if (isHeader) {
for(i=1; i<rows.length; i++)
rows[i].cells[cell.cellIndex].getElementsByTagName(""input"")[0].checked = sender.checked;
else {
var headerCheckBox = rows[0].cells[cell.cellIndex].getElementsByTagName(""input"")[0];
if (!sender.checked)
headerCheckBox.checked = false;
else {
for(i=1; i<rows.length; i++) {
if (!rows[i].cells[cell.cellIndex].getElementsByTagName(""input"")[0].checked) {
headerCheckBox.checked = false;
headerCheckBox.checked = true;

if (!Page.ClientScript.IsClientScriptBlockRegistered(typeof(Page), "GridViewCheckBox"))
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "GridViewCheckBox", script, true);

//adds onclick event handler
if (parentRow.RowType == DataControlRowType.Header)
this.Attributes["onclick"] = "gvCheckBoxClicked(this,true);";
else if (parentRow.RowType == DataControlRowType.DataRow)
this.Attributes["onclick"] = "gvCheckBoxClicked(this,false);";

That is all. In order to use just add the control to HeaderTemplate and ItemTemplate of the required column:
<asp:GridView ID="GridView1" runat="server" >
<wc:GridViewCheckBox id="GridViewCheckBox1" runat="server"/>

<wc:GridViewCheckBox id="GridViewCheckBox2" runat="server"/>
<asp:BoundField ...