Dirk Bergmann

Developer, panographer. Does consultancy work from own company. Lives in Chiang Mai, Thailand.

Twitter

Chiang Mai

Hua Hin

Thailand Hotels

ListVote - List. Vote. Learn.

Partnerseek - Find Partners

Validating Windows Forms Text Input

Unlike ASP.NET (which I'm more familiar with), Windows Forms don't have any "Validation Controls", so validating input has to be wired into the event model of your app. After some experimenting I found this procedure to work best for validating text box input:

1. Drop an ErrorProvider component onto your form. This component appears to have designer support when you drag it, however, it is not a control but a container-level component (like ImageList and ToolTip among others). The ErrorProvider component will display an error icon (ErrorProvider icon) next to the control that you specify programmatically during validation.

2. Handle the TextChanged Event
For TextBox validation, the preferred event is TextChanged as it lets you validate the contents of the control after they have been entered. Here's an example:

 The field of view can't be greater than a full circle (360 degrees):
image

 

 

 

 

 

If the user enters a letter, the error icon is displayed:

 

image

 

 

 

 

 

 

If the user enters a number too large, an error icon with a different message is displayed:

image

 

 

 

 

 

Here's the event handler for the TextChanged event:

 private void textBox1_TextChanged(object sender, EventArgs e)
        {
            if (!System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, @"^\d{1,3}$"))
            {
                errorProvider1.SetError(textBox1, "Please enter only up to three digits.");

            }
            else
            {
                if (float.Parse(textBox1.Text) > 360)
                {
                    errorProvider1.SetError(textBox1, "FOV cannot be larger than 360°");

                }
                else
                {
                    errorProvider1.SetError(textBox1, "");
                }
            }

        }

Regular expressions come to the fore here. The beginning of line (^) and end of line ($) characters in the pattern "^\d{1,3}$" are very important as otherwise the IsMatch function will return true as long as there is at least one decimal digit in the TextBox.Text.

Regular expression are cryptic which makes memorizing them hard. This article which accompanies the Expresso utility is great to refresh your memory. Hope it helps.

#

Theresa: I'm not easily irmpeessd. . . but that's impressing me! :)