我的代码仅在chckAll.Checked时才选中所有复选框...我要实现的是在未选中任何复选框的情况下,在选中所有复选框后将chckAll都选中了。选中一个复选框,而不是选中chckAll ...我该怎么做?
private void chckAll_CheckedChanged(object sender, EventArgs e)
{
if (chckAll.Checked)
{
foreach (Control ctrl in checkBoxesPanel3.Controls)
{
CheckBox chkboxes = ctrl as CheckBox;
if (chkboxes != null)
{
chkboxes.Checked = true;
}
}
}
}
最佳答案
将以下事件添加到除chckAll之外的所有其他复选框
private void checkBox_CheckedChanged(object sender, EventArgs e)
{
CheckFlg = true;
if (!CheckAllFlg)
{
chckAll.Checked = checkBoxesPanel3.Controls.OfType<CheckBox>().Where(x => x.Name != "chckAll").All(c => c.Checked);
}
CheckFlg = false;
}
private void chckAll_CheckedChanged(object sender, EventArgs e)
{
CheckAllFlg = true;
if (!CheckFlg)
{
foreach (CheckBox ctrl in checkBoxesPanel3.Controls.OfType<CheckBox>().Where(x => x.Name != "chckAll"))
{
ctrl.Checked = chckAll.Checked;
}
}
CheckAllFlg = false;
}
您需要定义两个属性,如下所示
public partial class Form1
{
public bool CheckAllFlg { get; set; }
public bool CheckFlg { get; set; }