I am using visual studio 2005 c#, and doing server side coding.
I have a checkbox template in my gridview. I have tried to assign a CheckAllCB button outside the gridview, so that whenCheckAllCB is clicked, the list of checkboxes in the item template will be checked.
However, it does not work and I am not able to spot the mistake.
Below is my code for my CheckAllCB button:
protected void CheckAllCB_CheckedChanged(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)GridView1.HeaderRow.FindControl("CheckAll");
if (chk.Checked)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chkrow = (CheckBox)GridView1.Rows[i].FindControl("UserSelector");
chkrow.Checked = true;
}
}
else
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chkrow = (CheckBox)GridView1.Rows[i].FindControl("UserSelector");
chkrow.Checked = false;
}
}
}
(SOLVED)
Thus I tried using a checkbox checkchange in the header template. However, when the checkbox CheckAll in header template is check changed, nothing happens in the checkboxes in the itemtemplate.
Below is my code for CheckAllCB in header template
private void ToggleCheckState(bool checkState)
{
// Iterate through the Products.Rows property
foreach (GridViewRow row in GridView1.Rows)
{
// Access the CheckBox
CheckBox cb = (CheckBox)row.FindControl("UserSelector");
if (cb != null)
cb.Checked = checkState;
}
}
protected void CheckAll_Click(object sender, EventArgs e)
{
ToggleCheckState(true);
}
protected void UncheckAll_Click(object sender, EventArgs e)
{
ToggleCheckState(false);
}
Anyone can help me identify the mistake I did in my method? Thank you
UserSelection item template:

CheckAllCB header template:

Added source code for GridView:
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" ondatabound="gv_DataBound" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="CheckAllCB" runat="server" OnCheckedChanged="CheckAllCB_CheckedChanged" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="UserSelection" OnCheckedChanged="UserSelector_CheckedChanged" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The problem is that the checkbox is declared as UserSelection in the page, but you are looking for UserSelector in codebehind.
Also, the header is declared as CheckAllCB in the page, but you are looking for CheckAll in the codebehind.
You need to change one or the other so that the names match.