sleekyeddie
sleekyeddie

Reputation: 21

C# error provider not working on textboxes in groupbox and tabcontrols

I am trying to implement using error provider to validate that my text boxes are not empty before proceeding with execution.

Error provider works on textboxes on the main form but refuses to work on any textbox or combo box that is in a groupbox or tabcontrol. It doesn't check the text boxes, it doesn't display error or waits until the user enter text/select item for the controls that are being checked.

Sure if I loose the groupbox or tabcontrol I would get the error check working as normal but I will also loose the benefit of using the groupbox and tab control for my application as I intended to.

I am using the code below to check if the textbox or combo box is empty/null.

Some help would be much appreciated, this has made me almost want to throw my computer out of the window.

private void button3_Click(object sender, EventArgs e)
{
       //Validate the text box in the form before proceeding to store in Database
       // var emptyornull = Controls.OfType<TextBox>().Where(box => box.Name.StartsWith("_")).OrderBy(box => box.TabIndex);
       // var emptyornull2 = Controls.OfType<ComboBox>().Where(box => box.Name.StartsWith("_")).OrderBy(box => box.TabIndex);

        var boxes = Controls.OfType<TextBox>();

        foreach (var testControl in boxes)
        {
            if (string.IsNullOrEmpty(testControl.Text))
            {
                this.errorProvider1.SetError((Control)testControl, "error");
                return;
            }

            this.errorProvider1.SetError((Control)testControl, (string)null);
        }
}

picture of a sample form

Upvotes: 1

Views: 1131

Answers (1)

user10216583
user10216583

Reputation:

This is because your code does not check the child controls and only checks the top level ones. You need to iterate through the Form's controls recursively:

private IEnumerable<Control> GetAllControls(Control control)
{
    var controls = control.Controls.Cast<Control>();
    return controls.SelectMany(ctrl => GetAllControls(ctrl)).Concat(controls);
}

private void button1_Click(object sender, EventArgs e)
{
    errorProvider1.Clear();
    foreach (Control c in GetAllControls(this))
    {
        if (c is TextBox && string.IsNullOrEmpty(c.Text))
            errorProvider1.SetError(c, "Error");
    }
}

Or, Linq way:

errorProvider1.Clear();

GetAllControls(this).Where(c => c is TextBox && string.IsNullOrEmpty(c.Text))
    .ToList()
    .ForEach(c => errorProvider1.SetError(c, "Error"));

Good luck.

Upvotes: 1

Related Questions