1

I have a C# Form that requires the user to fill in 4 textbox and select 3 combobox. I wanted to see if theres a simple way of validating that all of those fields are filled. If NOT then provide a message prompt stating which fields are missing.

I know i can use the code below, but wanted to see if there was something else

if (String.IsNullOrEmpty(TextBox.Text))
{
      MessageBox.Show("Enter Text Here.", "Error", MessageBoxButtons.OK, 
                                                 MessageBoxIcon.Warning);

}
4

1 回答 1

1

您可以使用此处解释的abatishchev解决方案遍历所有 TextBoxes 。

我在这一篇上背诵他:

定义一个扩展方法:

public static IEnumerable<TControl> GetChildControls(this Control control) where TControl : Control
{
    var children = (control.Controls != null) ? control.Controls.OfType<TControl>() : Enumerable.Empty<TControl>();
    return children.SelectMany(c => GetChildControls(c)).Concat(children);
}

然后像这样使用它:

var allTextBoxes = this.GetChildControls<TextBox>();

最后遍历它们:

foreach (TextBox tb in this.GetChildControls<TextBox>())
{
    if(String.IsNullOrEmpty(tb.Text)
    {
        // add textbox name/Id to array
    }
}

您可以将所有 TextBox Id 添加到一个集合中,并在最后使用此集合向用户显示需要填写哪些 Textboex。

编辑:

foreach 循环有点误导

你可以像这样使用它:

foreach (TextBox tb in this.GetChildControls<TextBox>()) { ... }

或者

foreach (TextBox tb in allTextBoxes) { ... } 

如果您事先将其保存到变量中。

于 2013-10-20T08:28:29.950 回答