1

I have a form with two panels that each have a [Save] button.

How can I validate all of the controls inside each panel separately?

I was hoping that the Panel class would have a Validate() method but it doesn't. It's also not a ContainerControl so it also doesn't have a ValidateChildren method.

What's the best way to accomplish this?

SofaKng
  • 1,063
  • 1
  • 11
  • 32
  • 2
    You will have to iterate through the controls in both panel's `Controls` property and validate each one manually. [This answer](http://stackoverflow.com/a/3793637/43846) may help. – stuartd Apr 14 '15 at 22:02

1 Answers1

1

If you set your Form's AutoValidate mode to EnableAllowFocusChange, and presuming you have validating events hooked up to each of the controls inside your panel, something like this:

private void tb_Validating(object sender, CancelEventArgs e)
{
    TextBox tb = sender as TextBox;
    if (tb != null)
    {
        if (tb.Text == String.Empty)
        {
            errorProvider1.SetError(tb, "Textbox cannot be empty");
            e.Cancel = true;
        }
        else
            errorProvider1.SetError(tb, "");                    
    }
}

Then on the Click handler for your save button, you can just do this:

private void SaveButton_Click(object sender, EventArgs e)
{
    foreach (Control c in panel1.Controls)
       c.Focus();
    // If you want to summarise the errors
    StringBuilder errorSummary = new StringBuilder();
    foreach (Control c in panel1.Controls){
        String error = errorProvider1.GetError(c);
        if (error != String.Empty) 
            errorSummary.AppendFormat("{0}{1}", errorProvider1.GetError(c), Environment.NewLine);
    }
    if(errorSummary.Length>0)
        MessageBox.Show(errorSummary.ToString());
}

That will cause the validation to fire on each of the controls within the panel.

Gary Wright
  • 2,441
  • 1
  • 20
  • 32
  • Thanks! That looks like it would work, but how would I check the validation status? – SofaKng Apr 15 '15 at 13:19
  • You mean whether any of the controls failed the validation? You could do that in lots of ways, but I have amended the answer with a suggestion – Gary Wright Apr 15 '15 at 13:45