首页 > 解决方案 > 如何从 foreach 循环中排除特定类型的控件?

问题描述

我正在尝试验证表单控件以查看它们是否为空,并在我的连击中发现了一个有趣的点。

List<string> emptycontrols = new List<string>();

foreach (Control control in Mainform.V_Datafield.Controls)
{
    if (control.Text.Contains(null))
    {
        emptycontrols.Add(control.Name);
    }
}
if (emptycontrols.Count > 0)
{
    MessageBox.Show("Empty fields detected:", emptycontrols.ToString()); 
}

以上是我的平庸解决方案,运行时会出现一个控件,即DateTimePicker控件永远不会为空,而且完全正确。

最终我的问题是我将如何DateTimePickerforeach循环中排除控件,以便它会忽略它但继续检查其他控件?

组框 ( V_datafield) 包含:

标签: c#

解决方案


foreach您可以随时在循环中进行如下检查

if (control is DateTimePicker)
     continue;

推荐阅读