如何创建 C# 的 "if" 语句中多个控件为 false 的方法?



简化这一点的最佳方法是什么(通过方法创建或其他方式(:

if ((radioButton1.Checked == false) && (radioButton2.Checked == false) && (radioButton1.Checked == false) && ...more similar controls... && ((radioButton99.Checked == false))
{ 
MessageBox.Show("Please select an option!);
}

感谢您的考虑。对于由此造成的任何不便或不满,我们深表歉意。

您可以将所有这些控件放在一个列表中,然后检查列表中是否有任何控件被选中。这可以通过多种方式完成。下面是其中两个的例子。

使用循环的示例:

bool optionSelected = false;
foreach(var control in controls) // the List is in this case called controls
{
if(control.Checked)
{
optionSelected = true;
}
}
// Check the boolean

使用 System.Linq 的示例:

if(!controls.Any(c => c.Checked))
{
MessageBox.Show("Please select an option!);
}

您需要将控件添加到公共集合中以简单地迭代它们。 如果你有一堆相同类型的控件,最好将它们放入窗体构造函数中的数组中:

CheckBox[] MyBoxes = new CheckBox[]{ check01, check02 , ... }
// MyBoxes is filled at Form_Load and it's usable in throughout of the form 
bool result = true;
for(int i=0; i<MyBoxes.Length; i++)
{ 
if (MyBoxes[i].Checked == false)
{  result = false; break; } 
}

另一种解决方案是在窗体上迭代整个控件:

bool result = true;
for(int i=0; i<this.Controls.Count; i++)
{ 
if (this.Controls[i] is CheckBox)
{
if ((this.Controls[i] as CheckBox).Checked == false)
{  result = false; break; } 
}
}

如果你有很多控件(在本例中 - 单选按钮(,那么你可以使用以下技巧 -Tag属性。

总结一下:

1( 使用 some 字符串设置Tag属性以与其他控件区分开来(特别是,可能存在并非必须处理一种类型的所有控件的情况(。

2( 在Tag中用定义的字符串收集这些控件并处理它们。

在特定情况下,您可以在Tag中设置字符串ToCheck,然后检查是否选中了所有单选按钮:

// Collect controls with defined string in Tag property
var radioButtons = this.Controls
.OfType<RadioButton>() //Filter controls by type
.Where(rb => ((string)rb.Tag) == "ToCheck"); //Get controls with defined string in Tag
// Check whether all RadioButtons are checked
bool allChecked = radioButtons.All(rb => rb.Checked);

可能的方法可能是引入变量进行条件验证

bool optionIsSelected = ((radioButton1.Checked == true) || (radioButton2.Checked == true)...;

然后在以下情况下使用它:

if (!optionIsSelected)
{ 
MessageBox.Show("Please select an option!);
}
private bool AreAllFalse(params bool[] thingsToCheck)
{
return things.All(t => !t);
}

用法

if (AreAllFalse(radioButton1.Checked,radiobutton2.Checked, etc)
{ 
//Do what you want
}

使用 params 关键字的好处是,它会在调用方法时为您创建数组。它还允许您只传入一件事来检查您是否愿意。虽然这在这里毫无意义,但它只是让事情变得棘手,并且值得了解

最新更新