如何在 Winform 中选中和取消选中复选框
本文关键字:复选框 取消 Winform | 更新日期: 2023-09-27 18:30:26
我的代码只在chckAll.选中时执行,而不是选中所有复选框...我想要实现的是,当任何复选框未选中时,选中所有复选框后,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; }