(Print this page)

The ErrorProvider Control (in Windows Forms)
Published date: Saturday, February 1, 2003
On: Moer and Éric Moreau's web site

Everyone has ever filled a form on the Web, either a survey, a registration, a taxation report, or maybe your expense report. Many of these page have validators (a mechanism that can validate on the client side if the data entered is valid (before going to server thus saving bandwidth). For years, programmers created many different methods to implement validation. Users had to get accustomed to each method. You may be surprised to know that .Net Windows Forms now implement this cool little feature quite easily. 

So this month column will introduce you to the ErrorProvider Control in Windows Forms.

First, I need to say that what we will use is a control but a special one. The ErrorProvider control extends about any existing controls, not just editable controls like the textbox but also buttons, labels, and almost all others! When you place a ErrorProvider control on a form, you can discover that almost all controls off the form have been extended.

Figure 1: The TextBox has new properties!

The ErrorProvider control, like the Timer control and the ToolTip control is invisible at runtime. Instead of overloading the form at design time with these controls, a new area has been created to receive them. This area is called the designer's component tray (and is normally located at the bottom of the form). This area simply aligns all these specials controls allowing you to select them when you need to work with them. Don't look for a strange place to find their properties. When you select one these controls, its properties are in the same usual spot in the properties dialog just like the textbox control.

Enough talking, let's do some code!

Before starting, I want to let you know that you can download complete and commented listing at the end of this article (instead of doing copy-and-paste of the code below).

The first thing we will explore is how to validate when the user click on a button (like a Save or a OK button). To do this, create a new VB.Net Windows application. On the form, add 2 TextBox controls (that you will name txtFName and txtLName), a ErrorProvider control, and a Button control (name it btnValidate). 

Now, in the code window, just after the "Windows Form Designer generated code" section, copy this snippet of code:

Private Sub btnValidate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnValidate.Click
    If txtFName.Text.Trim = "" Then
        ErrorProvider1.SetError(txtFName, "You must provide the first name.")
    Else
        ErrorProvider1.SetError(txtFName, "")
    End If

    If txtLName.Text.Trim = "" Then
        ErrorProvider1.SetError(txtLName, "You must provide the last name.")
    Else
        ErrorProvider1.SetError(txtLName, "")
    End If
End Sub
That's it! You are ready to run it. Start the application and press the Validate button without filling textboxes. You will see small icons (exclamation point into a red circle) appear to the right of both textboxes. If you place the mouse pointer over one of these icons, a tooltip will appear containing the message you set in the click event. Now, enter some data into the textboxes and press the button again. Both icons will disappear. It is so simple.

Have you notice that we put only one ErrorProvider control and the same control is bound to many other controls! The same ErrorProvider control can be used by many controls on the same form. In fact, the only reason why you should have more then one ErrorProvider Control is because you have different icons for different controls. 

Another thing you may want to change is the position of the icon. This setting is set of each control on not on the ErrorProvider control. Do you remember that adding the ErrorProvider control added properties to the controls on the form? One of these properties is the "IconAlignment On ErrorProvider1" which is MiddleRight by default but may be set to one of the six different value (a mix of left-right with top-middle-bottom).

Ready for live validation?

Validation done on the click of a button is perfect in the web world. In the Windows rich UI interface, you may want a faster validation. Why not validate on each changed in a textbox? Let's say we need the user to enter 2 values within specific range and validate the values as the user is typing. To do this, add 2 TextBox controls (name them txtNumber1 and txtNumber2 - set their Text property to 0). Copy this code and you are set:

Private Sub txtNumber1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtNumber1.TextChanged
    If Val(txtNumber1.Text) < 1 Or Val(txtNumber1.Text) > 100 Then
        ErrorProvider1.SetError(txtNumber1, "The number must be between 1 and 100.")
    Else
        ErrorProvider1.SetError(txtNumber1, "")
    End If
End Sub

Private Sub txtNumber2_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtNumber2.TextChanged
    If Val(txtNumber2.Text) < 101 Or Val(txtNumber2.Text) > 200 Then
        ErrorProvider1.SetError(txtNumber2, "The number must be between 101 and 200.")
    Else
        ErrorProvider1.SetError(txtNumber2, "")
    End If
End Sub

You can now run the application and play with the 2 later textboxes, you will see the error icon appear and disappear.

Validating a e-mail address

Let's do one more! This time, we will use a regular expression to validate that the e-mail address looks like a valid e-mail address. Add another TextBox to your form (name it txtEMail and set its Text property to a empty string).

Private Sub txtEMail_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtEMail.TextChanged
    If txtEMail.Text.Trim = "" Then
        ErrorProvider1.SetError(txtEMail, "You must provide a e-mail address.")
    ElseIf Not ValidateEMail(txtEMail.Text) Then
        ErrorProvider1.SetError(txtEMail, "You must provide a VALID e-mail address.")
    Else
        ErrorProvider1.SetError(txtEMail, "")
    End If
End Sub

Private Function ValidateEMail(ByVal pstrEMail As String) As Boolean
    Dim EmailRegex As System.Text.RegularExpressions.Regex = New System.Text.RegularExpressions.Regex("[\w-]+@([\w-]+\.)+[\w-]+")
    Dim M As System.Text.RegularExpressions.Match = EmailRegex.Match(pstrEMail)
    Return M.Success
End Function

You are ready for the testing! Try entering various combinations in the e-mail address TextBox. As you type, validation is done to be sure that it fits a valid e-mail address format.

Figure 2: The resulting application you can download.

Conclusion

With the help of the simple ErrorProvider control, you can now easily validate almost any control. Be sure to have a look at the BlinkRate and BlinkStyle properties of the control to change the blinking behaviour. The displayed icon can also be changed for any 16 by 16 icon you have by changing the Icon property.

I hope you appreciated the topic and see you next month.


(Print this page)