Introduction
Check/uncheck CheckBox control inside a GridView using javascript without postback. This article will give an idea on how to achieve this task.
Some sample code is provided under Using the code heading and complete code is available in the project download.
Background
(Forums are flooded with the questions about how to check/uncheck CheckBox control inside a GridView using javascript without postback.
How To’s:
In this article a GridView control is used. Inside the GridView control there are 3 fields. One template field and two are bound fields to display some sample data.
Inside the TemplateField a CheckBox control is placed in the HeaderTemplate (with ID cbSelectAll and Text Select All), ItemTemplate and AlternatingItemTemplate.
Using the code
Code that will be required to achieve this task.
Javascript that will be required to perform the Select All action is as follow:
<script type="text/javascript">
function <code>SelectAll(id)</code>
{
<code>var</code> grid = document.getElementById("<%= GridView1.ClientID %>");
<code>var</code> cell;
if (grid.rows.length > 0)
{
for (i=1; i<grid.rows.length; i++)
{
cell = grid.rows[i].cells[0];
for (j=0; j<cell.childNodes.length; j++)
{
if (cell.childNodes[j].type =="checkbox")
{
cell.childNodes[j].checked = document.getElementById(id).checked;
}
}
}
}
}
</script>
Code required to add an attribute of cbSelectAll CheckBox is as follow:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.GridView1.DataSource = FillDataTable();
this.GridView1.DataBind();
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
((CheckBox)e.Row.FindControl("cbSelectAll")).Attributes.Add("onclick", "javascript:SelectAll('" +
((CheckBox)e.Row.FindControl("cbSelectAll")).ClientID + "')");
}
}
Before clicking the Select All CheckBox
After clicking the Select All CheckBox