0

Overview of function.

I have this SaveDetails function within a WinForm, which iterates through all of the controls, to determine whether any errorProviders have been flagged in the form during the users input. If the function returns true, all of my TextBoxes values need to be stored in my private fields, and display a messsagebox and close the form.

// For about 15 textBoxes, Could this be achieved also by looping? As this looks very cumbersome.

title = cmb_Title.Text;

If returns false and an errorProvider has been found in the iteration, it needs to display an error message for the user, clear private fields and give the user chance to re-enter details, however not clear textBoxes!!

Issue:

the loop iterates through everything, all of the controls regardless if it has found an errorProvider. How can I stop this to just flag when just one has been found? This function is also in a clickEvent.

Code

isValid = true;
foreach (Control c in panel1.Controls)
{
    if (errorProvider1.GetError(c).Length > 0)
    {
        isValid = false;
        MessageBox.Show("invalid entry, please revisit the form before proceding");
    }
}
if (isValid)
{
    title = cmb_Title.Text;
    surName = txt_SurName.Text;
    dateOfBirth = dateTimePicker1.Text.ToString();

    MessageBox.Show("Indi Form Saved");
    Hide();
}
Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
  • 2
    It never makes any sense to use more than one ErrorProvider for a form. One is enough to provide icons and tooltips for all of the controls. You'll never have any trouble finding that one provider back of course. If you want to use ErrorProvider to *also* validate the entire form then [consider this](https://stackoverflow.com/a/2682478/17034). – Hans Passant Jun 07 '17 at 10:14

1 Answers1

0

you can shorten it using only TextBox controls and Linq.

Something like this:

List<TextBox> textBoxes = panel1.Controls.OfType<TextBox>().ToList();
if (textBoxes.Any(tb => !string.IsNullOrEmpty(errorProvider1.GetError(tb))))
    MessageBox.Show("invalid entry, please revisit the form before proceding");

If you don't want to check only TextBox controls but all controls in panel1, you can still use Linq to simplify your code.

var controlsList = panel1.Controls.Cast<Control>().ToList();
if (controlsList.Any(tb => !string.IsNullOrEmpty(errorProvider1.GetError(tb))))
    MessageBox.Show("invalid entry, please revisit the form before proceding");
Nino
  • 6,931
  • 2
  • 27
  • 42