这段代码有什么问题? combobox
为"Wholesale"
或"Retail"
,表单显示第二个语句(true,true)。如果我取消checkbox
else
作品(true
,false
)。知道为什么吗?
private void checkBox3_CheckedChanged(object sender, EventArgs e)
{
if (checkBox3.Checked == true || comboBox1.SelectedText == "Standalone")
{
this.checkBox1.BackColor = Color.Gray;
this.checkBox1.Enabled = false;
this.checkBox2.BackColor = Color.Gray;
this.checkBox2.Enabled = false;
}
if (checkBox3.Checked == true || comboBox1.SelectedText == "Retail")
{
this.checkBox1.BackColor = default(Color);
this.checkBox1.Enabled = true;
this.checkBox2.BackColor = default(Color);
this.checkBox2.Enabled = true;
}
else
{
this.checkBox1.BackColor = default(Color);
this.checkBox1.Enabled = true;
this.checkBox2.BackColor = Color.Gray
this.checkBox2.Enabled = false;
}
答案 0 :(得分:4)
一个简单的else if
和&&
的使用应该可以解决问题:
if (checkBox3.Checked == true && comboBox1.SelectedText == "Standalone")
{
...
//If this case is true, the following cases are not going to be checked
}
else if (checkBox3.Checked == true && comboBox1.SelectedText == "Retail")
{
...
//If this case is true, the following cases are not going to be checked
}
else
{
...
//No case before was true
}
请注意,if
后面的简单if
的使用不与else if
背后的if
的使用相同
另请注意,只有在第三个checkBox3_CheckedChanged
的状态发生更改后才会调用您的方法CheckBox
(除非您将该方法用于其他事件)
答案 1 :(得分:1)
我建议在此处取消所有$
并仅使用布尔公式进行操作。
首先,让我们摆脱讨厌的if
:
(checkBox3.Checked == true || comboBox1.SelectedText == "Standalone")
然后尝试猜测 bool isRetail = checkBox3.Checked && comboBox1.SelectedText == "Retail";
bool isStandalone = checkBox3.Checked && comboBox1.SelectedText == "Standalone";
应该是CheckBox
:
Enabled
最后,我们应该更新他们的 // checkBox2 is enabled if and only if isRetail
//TODO: can see, how checkBox2 is unreadable? Change the name into, say "boxIsRetail"
this.checkBox2.Enabled = isRetail;
// checkBox2 is enabled if and only if neither isRetail nor isStandalone
//TODO: can see, how checkBox1 is unreadable? Change the name into, say "boxIsNeither"
this.checkBox1.Enabled = !(isRetail || isStandalone);
。 Color
的{{1}}仅取决于CheckBox
:
Color
将所有内容放在一起
Enabled
请注意,您可以轻松添加其他 this.checkBox1.BackColor = this.checkBox1.Enabled ? default(Color) : Color.Gray;
this.checkBox2.BackColor = this.checkBox2.Enabled ? default(Color) : Color.Gray;
变量,例如 private void checkBox3_CheckedChanged(object sender, EventArgs e) {
bool isRetail = checkBox3.Checked && comboBox1.SelectedText == "Retail";
bool isStandalone = checkBox3.Checked && comboBox1.SelectedText == "Standalone";
checkBox2.Enabled = isRetail;
checkBox1.Enabled = !(isRetail || isStandalone);
//TODO: these lines are good candidate to be extracted into a method "UpdateColor"
checkBox1.BackColor = checkBox1.Enabled ? default(Color) : Color.Gray;
checkBox2.BackColor = checkBox2.Enabled ? default(Color) : Color.Gray;
}
,bool
等,并在isWholesale
{{{{ 1}}和isReserved