whatdoyouNeedFromMe
whatdoyouNeedFromMe

Reputation: 105

Iterate through Controls to find errorProviders c# WinForm

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

Upvotes: 0

Views: 404

Answers (1)

Nino
Nino

Reputation: 7095

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

Upvotes: 0

Related Questions