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

use*_*373 1 c# checkbox winforms

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

                    }

                }

            }           

        }
Run Code Online (Sandbox Code Playgroud)

Dam*_*ith 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;
}
Run Code Online (Sandbox Code Playgroud)

您需要定义两个属性,如下所示

public partial class Form1
{
    public bool CheckAllFlg { get; set; }
    public bool CheckFlg { get; set; }
Run Code Online (Sandbox Code Playgroud)