Here is the code how to put a check all checkbox in the Column Header of the datagrid so that when the user clicks it all the checkboxes in all rows below also get checked. Also, the cool thing is that this will happen on the client side using javascript without any postbacks.
Default.aspx
DataGrid
<asp:DataGrid ID="dg1" AutoGenerateColumns="False" Width="100%" Runat="server">
<Columns>
<asp:TemplateColumn>
<HeaderTemplate>
<input ID="chkAll" type="checkbox" onclick="CheckAllDataGridCheckBoxes('chkItem',this.checked)">
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkItem" Runat="server"></asp:CheckBox>
</ItemTemplate>
<ItemTemplate>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:datagrid>
Function:CheckAllDataGridCheckBoxes
<script language="javascript" type="text/javascript" >
function CheckAllDataGridCheckBoxes(aspCheckBoxID, checkVal)
{
debugger;
re = new RegExp(':' + aspCheckBoxID + '$') //generated control name starts with a colon
for(i = 0; i < form1.elements.length; i++)
{
item = document.forms[0].elements[i]
if (item.type == 'checkbox')
{
if (re.test(item.name))
item.checked = checkVal;
}
}
}
</script>
Default.aspx.cs
Hashtable ht = new Hashtable();
ht.Add( "1", "A1" );
ht.Add( "2", "A2" );
ht.Add( "3", "A3" );
ht.Add( "4", "A4" );
ht.Add( "5", "A5" );
ht.Add( "6", "A6" );
dg1.DataSource = ht;
dg1.DataBind();

0 comments:
Post a Comment