Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleUse validation events in VB .NET
Description
Keywordsvalidate, validation, Validating, Validated
CategoriesVB.NET, Software Engineering
 
Use the Validating event to see if a control contains a valid value. If it does not, set the event handler's e.Cancel value to True to cancel the event that is trying to move out of the control. Optionally select theh offending text (for example, in a TextBox). Then use an ErrorProvider control's SetError method to flag the control's value as invalid.

The Validated event handler executes when a control is successfully validated. Use the ErrorProvider's SetError method to clear any previous error for that control.

This example displays three TextBoxes. The first has the following event handlers thuat veify that it contains five digits. The second has its CausesValidation property set to False while the third has CausesValidation = True.

Enter a value in the first TextBox. If you move to the second TextBox, nothing happens because it has CausesValidation = False. When you move to the third TextBox, the Validating event fires and the fun begins.

 
' Validate the ZIP code.
Private Sub txtZip_Validating(ByVal sender As Object, ByVal _
    e As System.ComponentModel.CancelEventArgs) Handles _
    txtZip.Validating
    ' See if the text is 5 digits.
    If Not (txtZip.Text Like "#####") Then
        ' The Zip code is invalid.
        ' Cancel the event moving off of the control.
        e.Cancel = True

        ' Select the offending text.
        txtZip.Select(0, txtZip.Text.Length)

        ' Give the ErrorProvider the error message to
        ' display.
        ErrorProvider1.SetError(txtZip, "Invalid ZIP code " & _
            "format")
    End If
End Sub

' The ZIP code is valid. Clear the error.
Private Sub txtZip_Validated(ByVal sender As Object, ByVal _
    e As System.EventArgs) Handles txtZip.Validated
    ErrorProvider1.SetError(txtZip, "")
End Sub
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated