Check/Uncheck checkboxes in GridView using javascript
------------------------------------------- .aspx code ---------------------------------------------
<script type="text/javascript">
function SelectAll(id)
{
var frm = document.forms[0];
for (i=0;i<frm.elements.length;i++)
{
if (frm.elements[i].type == "checkbox")
{
frm.elements[i].checked = document.getElementById(id).checked;
}
}
}
</script>
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" Width="400px">
<Columns>
<asp:TemplateField>
<AlternatingItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</AlternatingItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
<HeaderTemplate>
<asp:CheckBox ID="cbSelectAll" runat="server" Text="Select All" />
</HeaderTemplate>
<HeaderStyle HorizontalAlign="Left" />
<ItemStyle HorizontalAlign="Left" />
</asp:TemplateField>
</Columns>
</asp:GridView>
----------------------------------------- .vb file if VB.Net is the language ------------------------------------------
VB.Net Code
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
If (e.Row.RowType = DataControlRowType.Header) Then
'adding an attribut for onclick event on the check box in the hearder and passing the ClientID of the Select All checkbox
DirectCast(e.Row.FindControl("cbSelectAll"), CheckBox).Attributes.Add("onclick", "javascript:SelectAll('" & DirectCast(e.Row.FindControl("cbSelectAll"), CheckBox).ClientID & "')")
End If
End Sub
----------------------------------------- .cs file if C#.Net is the language ------------------------------------------
C#.Net Code
protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if ((e.Row.RowType == DataControlRowType.Header))
{
//adding an attribut for onclick event on the check box in the hearder and passing the ClientID of the Select All checkbox
((CheckBox)e.Row.FindControl("cbSelectAll")).Attributes.Add("onclick", "javascript:SelectAll('" + ((CheckBox)e.Row.FindControl("cbSelectAll")).ClientID + "')");
}
}