CAD
CAD

Reputation: 4292

User input validation with a foreach loop in form constructor

I'm trying to use this custom method for user input validation in text boxes. But I feel something missing in this approach. Now use cant move to next text box if the validation failed. Is this a good thing or bad thing to do?

private void textBox_Validating(object sender, CancelEventArgs e)
{
    TextBox currenttb = (TextBox)sender;
    if (currenttb.Text == "")
    {
        MessageBox.Show(string.Format("Empty field {0 }", currenttb.Name.Substring(3)));
        e.Cancel = true ;
    }

    else
    {
        e.Cancel = false;
    }
}

Adding the handler to the textboxes with a foreach loop in the form constructor:

foreach(TextBox tb in this.Controls.OfType<TextBox>().Where(x => x.CausesValidation == true))
{
    tb.Validating += textBox_Validating;
}

Upvotes: 0

Views: 480

Answers (2)

Peter Liang
Peter Liang

Reputation: 97

I thought it would be a bad user experience if you popup too much message box. May be you should consider use labels to display error message beside each text box. In your programm, I can't even close the window by clicking the close button if I left the text box empty.

Upvotes: 1

Prisoner
Prisoner

Reputation: 1857

How about using Error Provider, it will display exclamation if validation fail

Upvotes: 1

Related Questions