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

夙愿已清 提交于 2019-12-11 16:59:09

问题


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


回答1:


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:

//This beautiful function By @RezaAghaei
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.



来源:https://stackoverflow.com/questions/58899390/c-sharp-error-provider-not-working-on-textboxes-in-groupbox-and-tabcontrols

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!