如何在Winform中选中和取消选中复选框?

时间:2013-09-06 02:54:44

标签: c# winforms checkbox

我的代码仅在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;

                    }

                }

            }           

        }

1 个答案:

答案 0 :(得分:5)

将以下事件添加到除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; }