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

}
slugster
  • 49,403
  • 14
  • 95
  • 145
hex c
  • 705
  • 2
  • 13
  • 22

1 Answers1

1

You could iterate over all TextBoxes by using abatishchev solution explained here.

I am reciting him on this one:

Define an extension method:

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

Then use it like this:

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

and finally loop through them:

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

You can add all TextBox Ids into a collection and use this collection at the end to show the user which Textboexs need to be filled up.

EDIT:

The foreach loop is a bit misleading

You can use it like this:

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

or

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

if you have saved it to a variable beforehand.

Community
  • 1
  • 1
Marco
  • 22,856
  • 9
  • 75
  • 124