Subscribe to Sergio Tapia - Lost in the GC.        RSS Feed
-----

It's 6:26pm, do you know where your validation is? Validating Winforms.

Icon 3 Comments
I'm sure there are many ways to skin this proverbial cat, but I've worked on it for a bit and I feel I like this approach. It's easy to modify, easy to follow along with and allows for some cool GUI manipulations. Well, as far as you can get with Windows Forms anyway.

Here's a screenshot of how it looks when someone tries to act smart and corrupt our precious database!

Posted Image

Here's how to do it.

First, create your form. Drag a couple of textboxes in there, or just follow along with me. I've created two for string values, and one that's supposed to only allow for numbers.

Next, in the Form constructor, let's assign our event handlers.

public Form1()
{
    InitializeComponent();
    txtFirstName.Validating += StringValidation;
    txtFirstName.Validated += StringValidated;

    txtLastName.Validating += StringValidation;
    txtLastName.Validated += StringValidated;

    txtAge.Validating += NumericValidation;
    txtAge.Validated += NumericValidated;
}



Notice we have a StringValidation and a StringValidated. The former is used on the fly to validate the inputs, and the latter is fired when everything went OK and the control passed validation.

Important: The Validation event only fires when the control LOSES focus. It doesn't fire as they type.

Let's now create these handlers:

private void StringValidation(object sender, CancelEventArgs e)
{
    if (!((TextBox)sender).Text.All(Char.IsLetter) || String.IsNullOrEmpty(((TextBox)sender).Text))
    {
        e.Cancel = true;
        this.errorProvider1.SetError(((Control)sender), "Must contain only letters.");
        ((Control)sender).BackColor = Color.Red;
    }
}

private void StringValidated(object sender, EventArgs eventArgs)
{
    this.errorProvider1.SetError(((Control)sender), "");
    ((Control)sender).BackColor = Color.White;
}

private void NumericValidation(object sender, CancelEventArgs e)
{
    string value = ((TextBox) sender).Text;
    int result;
    if (!int.TryParse(value, out result) || String.IsNullOrEmpty(((TextBox)sender).Text))
    {
        e.Cancel = true;
        this.errorProvider1.SetError(((Control)sender), "Must contain only numbers.");
        ((Control) sender).BackColor = Color.Red;
    }
}

private void NumericValidated(object sender, EventArgs e)
{
    this.errorProvider1.SetError(((Control)sender), "");
    ((Control) sender).BackColor = Color.White;
}



Great, so now we have our inputs hooked to our validation events, and when they don't pass the validation, we change the backcolor to a horrible red. Hopefully waking up Mrs. Doris the 47 year old secretary from her boredom induced coma.

The final step is to validate the entire form prior to submitting it somewhere. For example, in this form lets say we want to save whatever Mrs. Doris typed in to some database somewhere.

Luckily the Form class has a nifty little method called ValidateChildren which validates all selectable child controls in the form.

private void btnSubmit_Click(object sender, EventArgs e)
{
    if (this.ValidateChildren())
    {
        MessageBox.Show("Everything is valid.");
        //Send data to Foxpro 1998 database.
    }
}



I hope you guys followed along easy enough and I made things clear for you. I'm eager to hear alternatives or maybe about a pattern that makes things cleaner. As it stands this is great for a demo, but for a bigger project I can easily see this cluttering up the classes.

Thanks for reading!

3 Comments On This Entry

Page 1 of 1

scalt Icon

13 April 2011 - 06:49 PM
Awesome little tut, never realised there was a 'validation' type series of events
0

Sergio Tapia Icon

13 April 2011 - 07:02 PM
You can even switch the icon that displays. :)

Posted Image
0

Shane Hudson Icon

14 April 2011 - 02:56 AM
Very nice! This has shown me just how ugly my validation can be!
0
Page 1 of 1

Trackbacks for this entry [ Trackback URL ]

There are no Trackbacks for this entry

1 user(s) viewing

1 Guests
0 member(s)
0 anonymous member(s)

About Me

Posted Image


Bienvenidos! I'm a USA ex-pat living in Bolivia for the past 10 years. Web development is my forte with a heavy lean for usability and optimization. I'm fluent in both English and Spanish. I guest write for the popular Python website Python Central. Visit my website.

Categories