1

I have a Form that contains a TabControl and an ErrorProvider. One of the tabs has several textboxes and a button. The textboxes use the Validating event to SetError() if contents are not valid. When the button is pressed, this runs:

 bool ok = true;
 foreach (Control c in errorProviderDv.ContainerControl.Controls)
 {
    MessageBox.Show(c.Name);
    if (errorProviderDv.GetError(c) != "")
    {
        ok = false;
    }
 }

The TabControl is the only control in errorProviderDv.ContainerControl.Controls, even though several errors are set and are displaying in the form.

Am I doing something wrong? Does the ErrorProvider need to be a child of the tab instead of the form?

Kevin S. Miller
  • 913
  • 1
  • 9
  • 21
  • 1
    You can not assign `TabControl` or `TabPage` as `ContainerControl` or `ErrorProvider`. What's your requirement? Do you want to know the validation state of the whole `Form` or only that specific `TabPage` of the `TabControl`? – Reza Aghaei Aug 05 '16 at 07:59
  • I'm just looking at one TabPage at a time. I have a different ErrorProvider for each TabPage. – Kevin S. Miller Aug 05 '16 at 13:51
  • 1
    You don't need to use multiple `ErrorProvider` components. One of them is enough for the whole form. Anyway, you can change the foreach to look in `(Control c in Control c in tabControl1.TabPages[0].Controls)` if you want to check those controls. – Reza Aghaei Aug 05 '16 at 21:18
  • Also take a look at this post, you may find it useful: [Validating user input / Give .NET controls status OK or NOK](http://stackoverflow.com/a/35993185/3110834) – Reza Aghaei Aug 05 '16 at 21:26
  • 1
    The controls hierarchy is a *tree*, not an array or collection. Trees are always best traversed with recursion, use `c.Controls`. Or consider [this approach](http://stackoverflow.com/questions/2682136/c-sharp-winforms-errorprovider-control/2682478#2682478). – Hans Passant Aug 05 '16 at 21:59

1 Answers1

0

The TabControl itself is a container which contains TabPages. Those TabPages are containers which contain your textboxes.

The following code will get you want you want but you may want to clean it up to make a recursive call passing in a container so it will work for almost any type.

    private void button1_Click(object sender, EventArgs e)
    {
    bool ok = true;
    foreach (Control c in errorProviderDv.ContainerControl.Controls)
    {
        if (c is TabControl)
        {
            foreach (Control t in (c as TabControl).SelectedTab.Controls)
            {
                MessageBox.Show(t.Name);
                if (errorProviderDv.GetError(t) != "")
                {
                    ok = false;
                }
            }
        }
    }
}
Scott Wylie
  • 4,725
  • 2
  • 36
  • 48