C# 如何检查多个组合框值是否为空

C# 如何检查多个组合框值是否为空,c#,winforms,combobox,C#,Winforms,Combobox,我在我的win form应用程序中有40个组合框,我想在按钮点击结束时检查所有组合框值是否已输入,即没有选择任何组合框值为空 我尝试下面的代码用于每个循环,但找不到成功 foreach (Control c in this.Controls) { if (c is ComboBox) { ComboBox textBox = c as ComboBox; if (textBox.SelectedValue==string.Emp

我在我的win form应用程序中有40个组合框,我想在按钮点击结束时检查所有组合框值是否已输入,即没有选择任何组合框值为空

我尝试下面的代码用于每个循环,但找不到成功

foreach (Control c in this.Controls)
{
      if (c is ComboBox)
      {
           ComboBox textBox = c as ComboBox;
           if (textBox.SelectedValue==string.Empty)
           {
               MessageBox.Show("please fill all fields");
           }
      }
}

因此,如何在简单的代码行中实现此验证

尝试使用linq和递归:

var isAnyEmpty = ScanForControls<ComboBox>(this)
   .Where(x => x.SelectedIndex < 0)
   .Any();

if (isAnyEmpty)
    MessageBox.Show("please fill all fields");
var isAnyEmpty=ScanForControls(此)
.其中(x=>x.SelectedIndex<0)
.Any();
如果(isAnyEmpty)
MessageBox.Show(“请填写所有字段”);
和递归搜索:

public IEnumerable<T> ScanForControls<T>(Control parent) where T : Control
{
    if (parent is T)
        yield return (T)parent;

    foreach (Control child in parent.Controls)
    {
        foreach (var child2 in ScanForControls<T>(child))
            yield return (T)child2;
    }
}
public IEnumerable ScanForControls(控件父级),其中T:Control
{
if(父项为T)
收益率(T)母公司;
foreach(父控件中的控件子控件)
{
foreach(ScanForControls(child)中的var child2)
收益率(T)2;
}
}

要确保选中表单中的每个组合框,您必须遍历表单中的每个控件,请尝试此操作

private void button1_Click(object sender, EventArgs e)
{
   foreach (Control c in this.Controls)
   {
      if (c is ComboBox)
      {
         ComboBox textBox = c as ComboBox;
         if (textBox.SelectedValue == null)
         {
            MessageBox.Show("please fill all fields");
            break;
         }
       }
       else
          recursiveComboboxValidator(c);
    }
}

void recursiveComboboxValidator(Control cntrl)
{
    foreach (Control c in cntrl.Controls)
    {
       if (c is ComboBox)
       {
           ComboBox textBox = c as ComboBox;
           if (textBox.SelectedValue == null)
           {
                MessageBox.Show("please fill all fields");
                break;
           }
        }
        else
            recursiveComboboxValidator(c);
     }
}

this.control
只允许您访问表单中的控件,但如果您的组合嵌套在某个面板或其他面板中,它将跳过winform pageI的tabcontrols中的combobox我忘记了
AsEnumerable
调用,添加了它。this.controls.AsEnumerable()显示错误,此.error…..不包含可枚举的定义….对此感到抱歉:(您需要
Cast
而不是
asenuable()
,我现在检查过了。啊!你需要递归搜索,请查看我的更新答案。哇,这对我来说很好,谢谢,你能解释一下这个代码吗每次都会显示messagebox,即即使我选择allcombobox,也会显示错误“请填写所有字段”4次,因为我有4个tabcontrolsit,如果组合框中的项目没有分配任何值,您将如何填充这些组合框??