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

前端 未结 1 1583
萌比男神i
萌比男神i 2020-12-22 09:17

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 th

1条回答
  •  醉梦人生
    2020-12-22 09:58

    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 GetAllControls(Control control)
    {
        var controls = control.Controls.Cast();
        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.

    0 讨论(0)
提交回复
热议问题