Export (0) Print
Expand All

Validation of Control Data on Windows Forms

Visual Studio .NET 2003

You often want to check if the information users enter into a Windows Form is valid. For example, if you have a TextBox control for a phone number, you can check that it contains only the appropriate characters (numbers, parentheses, hyphens and so forth). Frequently, you use regular expressions to validate data entered by the user. For more information on regular expressions, see .NET Framework Regular Expressions. For examples using regular expressions, see Regular Expression Examples.

Validation In Action

To validate the contents of a control. you write code to handle the Validating event. In the event handler, you test for a certain condition (such as the phone number example from above). Validation is one of a series of events that occurs during processing. For more details, see Control.Validating Event.

If the test fails, you set the Cancel property of the Validating event's CancelEventArgs to True. This cancels the Validating event and causes the focus to return to the control. The practical effect is that the user cannot leave the control until the data is valid. For more information on validating the contents of controls, see Code: Validating User Input on Windows Forms (Visual Basic).

Closing The Form and Overriding Validation

A side effect of the control maintaining focus when data is invalid is that it is impossible to close the parent form in any of the usual ways you close a form:

  • Clicking the Close box
  • Via the System menu that appears when you right-click the title bar
  • Calling the Close method programmatically

However, in some cases, you might want to allow the user to close the form regardless of whether the values in the controls are valid. You can override validation and close a form that still contains invalid data by creating a handler for the form's Closing event. In the event, set the Cancel property to False. This forces the form to close.

Note   If you force the form to close in this way, any information in the controls that has not already been saved is lost.
Note   Modal forms do not validate the contents of controls when closed. You can still use control validation to lock focus to a control, but you do not need to be concerned with the behavior with regard to closing the form.

See Also

Code: Validating User Input on Windows Forms (Visual Basic) | Code: Overriding Control Validation on Windows Forms in the Closing Event (Visual Basic) | Form.Closing Event | CancelEventArgs Class

Show:
© 2014 Microsoft