首页 > 解决方案 > 如何在 C# 的“if”语句中创建多个控件为假的方法?

问题描述

简化此操作的最佳方法是什么(通过方法创建或其他方式):

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

谢谢您的考虑。对造成的任何不便或不满深表歉意。

标签: c#if-statementcontrols

解决方案


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

使用循环的示例:

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!);
}

推荐阅读