0

Is there a way that I can check my "check all button" and, then, when I check one of my items in the CheckBox list, the "check all button" will be unchecked but the items are still checked?

RolandoMySQLDBA
  • 43,883
  • 16
  • 91
  • 132

1 Answers1

0

Following will do the trick:

<asp:CheckBox ID="CheckAllCheckBox" runat="server" Text="Select All" AutoPostBack="true" />
<br />
<asp:CheckBoxList ID="MyCheckBoxList" runat="server" AutoPostBack="true">
    <asp:ListItem>One</asp:ListItem>
    <asp:ListItem>Two</asp:ListItem>
    <asp:ListItem>Three</asp:ListItem>
</asp:CheckBoxList>

And the code:

protected void Page_Load(object sender, EventArgs e)
{
    CheckAllCheckBox.CheckedChanged += CheckAllCheckBox_CheckedChanged;
    MyCheckBoxList.SelectedIndexChanged += MyCheckBoxList_SelectedIndexChanged;
}

void MyCheckBoxList_SelectedIndexChanged(object sender, EventArgs e)
{
    if (MyCheckBoxList.Items.Cast<ListItem>().Where(i => i.Selected).Count() == MyCheckBoxList.Items.Count)
        CheckAllCheckBox.Checked = true;
    else
        CheckAllCheckBox.Checked = false;
}

void CheckAllCheckBox_CheckedChanged(object sender, EventArgs e)
{
    SetCheckedState(CheckAllCheckBox.Checked);
}

private void SetCheckedState(bool setChecked)
{
    foreach (var item in MyCheckBoxList.Items.Cast<ListItem>().Where(i => i.Selected != setChecked))
        item.Selected = setChecked;
}
Abbas
  • 14,186
  • 6
  • 41
  • 72
  • 1
    Posting back to do nothing but change the select state of checkboxes seems excessive. – MikeSmithDev Feb 08 '13 at 18:40
  • The poster did not specify whether to use JS or not, so I gave him an option that works. Of cours using jQuery to achieve the same will performance-wise certainly be a better option. – Abbas Feb 08 '13 at 19:41
  • How about if i have 2 checkboxlist with different data that has "Check all" button each? – user2055309 Feb 08 '13 at 20:29
  • You'll have twice the code I gave you. If you mean to say that one "Select All"-checkbox should work for both lists, implement the same code but for the other CheckBoxList. – Abbas Feb 08 '13 at 20:47