0

我有 3 个复选框,如果选中一个,我可以关闭其中两个。但我希望如果选中第三个,那么应该关闭前两个。我怎样才能做到这一点?

这就是我正在尝试的。

private void chkResFoodVeg_CheckedChanged(object sender, EventArgs e)
{
    //disables the other checkbox if one is checked
    this.chkResFoodNveg.Enabled = !this.chkResFoodVeg.Checked;
}

private void chkResFoodNveg_CheckedChanged(object sender, EventArgs e)
{
    this.chkResFoodVeg.Enabled = !this.chkResFoodNveg.Checked;
}

private void chkResFoodBoth_CheckedChanged(object sender, EventArgs e)
{
    this.chkResFoodBoth.Enabled = !this.chkResFoodNveg.Checked &&
   !this.chkResFoodVeg.Checked;
}

代码的最后一部分不起作用。它应该关闭前两个复选框。

谢谢

4

2 回答 2

1

您的逻辑是倒退的,您需要两个分配而不是组合输入。

private void chkResFoodBoth_CheckedChanged(object sender, EventArgs e)
{
    this.chkResFoodNveg.Enabled = !this.chkResFoodBot.Checked;
    this.chkResFoodVeg.Enabled = !this.chkResFoodBot.Checked;
}

但是,从您描述按钮操作的方式来看,听起来您正在尝试模拟RadioButton的行为,也许您应该改用它。它只会让您一次选择 3 个选项之一。

在此处输入图像描述

于 2013-09-15T23:54:27.027 回答
1

看起来像是RadioButton的工作!尽管可以使用CheckBox来实现您想要的- 它可能是这项工作的错误工具。

将这些添加到 Windows 窗体会自动实现您想要的功能,只要它们属于相同的容器对象,例如GroupBoxPanel

使用中的单选按钮示例

于 2013-09-16T00:38:43.723 回答