有没有办法检查我的“检查所有按钮”,然后,当我在CheckBox列表中检查我的一个项目时,“检查所有按钮”将被取消选中,但仍检查项目?< / p>
答案 0 :(得分:0)
以下将诀窍:
<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>
代码:
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;
}