Validation of Control Data on Windows Forms

You often want to determine whether the information that users enter into a Windows Form is valid. For example, if you have a TextBox control for a telephone number, you may want to verify that it contains only the appropriate characters (numbers, parentheses, hyphens, and so forth).

Validation in Action

To validate the contents of a control, you write code to handle the System.Windows.Forms.Control.Validating event. In the event handler, you test for a certain condition (for example, the validity of the telephone number). 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 additional information and another example, see System.Windows.Forms.Control.Validating.

You can use regular expressions to validate the data entered by the user. For more information about regular expressions, see .NET Framework Regular Expressions. For examples of using regular expressions, see Regular Expression Examples.

Closing the Form and Overriding Validation

When the control maintains focus because the data it contains is invalid, it is impossible to close the parent form in one of the usual ways:

  • By clicking the Close box.

  • By using the System menu that appears when you right-click the title bar.

  • By calling the Close method programmatically.

However, in some cases, you might want to let the user 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. For more information and an example, see System.Windows.Forms.Form.Closing.

NoteNote

If you force the form to close in this manner, any information in the form's controls that has not already been saved is lost. In addition, modal forms do not validate the contents of controls when they are closed. You can still use control validation to lock focus to a control, but you do not have to be concerned about the behavior associated with closing the form.

See Also

Reference

System.Windows.Forms.Control.Validating
System.Windows.Forms.Form.Closing
System.ComponentModel.CancelEventArgs

Concepts

User Input Validation in Windows Forms