ASP.NET 'Check all checkboxes' control

Posted by RUiHAO on Stack Overflow See other posts from Stack Overflow or by RUiHAO
Published on 2011-11-21T01:35:34Z Indexed on 2011/11/21 1:50 UTC
Read the original article Hit count: 123

Filed under:
|

I am using visual studio 2005 c#, and doing server side coding.

I have a list of checkboxes in my gridview via checkbox template. I have tried to assign a checkbox in my header template, and assigned a checkbox_checkchange method to make it such that when the checkbox at the header is checked, the list of checkboxes in the template will be checked as well. However, it does not work and I am not able to spot the mistake.

Below is my code for my checkbox in header template:

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;
        }
    }
}

Thus I tried using a button to assign the checkall command instead. However, when I clicked on the button, the page does nothing but just refreshes itself. Below is my code for the checkall and uncheckall button:

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 GridView template: enter image description here

© Stack Overflow or respective owner

Related posts about c#

Related posts about ASP.NET