0

I have 5 error provider controls in my form which correspond to 5 text boxes, I am trying to loop through each text box and perform some validation on it such as if the text box is empty.

If a textbox is empty I would like the corresponding error provider control to display an error message, however I am having trouble when it comes to how to increment the errorprovider, such as errorProvider[count] where count would get incremented after each validation loop.

 private void ValidateForm(){
    int count = 1;
    foreach (TextBox tb in this.Controls.OfType<TextBox>()){
        if(string.IsNullOrWhiteSpace(tb.Text)){
           errorProvider1.SetError(tb, "Please enter a value");
           //errorProvider[count].SetError(tb, "Please enter a value");
        }
        count ++;
    }
 }
sanduniYW
  • 723
  • 11
  • 19
Eznx
  • 37
  • 1
  • 6
  • Start fixing this by using only *one* ErrorProvider, there is no advantage to using more than one. Next, take a look at [this Q+A](https://stackoverflow.com/a/2682478/17034). – Hans Passant Sep 18 '18 at 08:33

1 Answers1

0

As a quick patch, you can try using Reflection:

  using System.Reflection;

  ...

  foreach (TextBox tb in this.Controls.OfType<TextBox>()) {
    ...
    // Obtain errorProvider[count] via Reflection
    ErrorProvider provider = GetType()
      .GetField($"errorProvider{count}", BindingFlags.Instance | BindingFlags.NonPublic)
      .GetValue(this) as ErrorProvider;

    provider.SetError(tb, "Please enter a value");
    ... 
  }

In case of more elaborated solution, you can organize the ErrorProviders into a collection, say, array:

  private ErrorProvider[] m_Providers;

  public MyForm() {
    InitializeComponent();

    //TODO: Think on which providers should be included
    m_Providers = new ErrorProvider[] {
      errorProvider1,
      errorProvider2,  
      errorProvider3,
      errorProvider4,
      errorProvider5,
    };
  }

Then you can put

  foreach (TextBox tb in this.Controls.OfType<TextBox>()) {
    ...
    // Now, errorProviderCount can be taken from the collection
    m_Providers[count - 1].SetError(tb, "Please enter a value");
    ...
  }
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215