Previous Page
Next Page

Validating Data

The concept of input validation is simple enough, but it is not always easy to implement, especially if validation involves cross-checking data the user has entered into two or more controls. The underlying business rule might be relatively straightforward, but all too often, the validation is performed at an inappropriate time making the form difficult (and often infuriating) to use.

The CausesValidation Property

Windows forms and controls have a Boolean property called CausesValidation that indicates whether the form or control raises validation events. If the property is set to true (which is the default) for a control, when that control receives the focus, the previous control (the one losing the focus) will be validated. If the validation fails, the focus will return to the previous control. It is important to realize that the CausesValidation property does not apply to the control itself but instead affects all the other controls on the form. If you are feeling a little confused by this statement, don't panic—you will see an example in a moment.

Validation Events

To validate data in a control, you can use two events: Validating and Validated. The Validating event occurs when focus leaves a control and attempts to switch to a control that has its CausesValidation property set to true. You can use the Validating event to examine the value of the control losing the focus. If you don't like what you see, you can set the Cancel property of the CancelEventArgs parameter to prevent the focus from changing. It would probably also help to report the reason why the validation failed.

The Validated event occurs after the Validating event (as long as it was not canceled) but before the control loses focus. You cannot cancel this event, so it is not as useful as the Validating event for checking the user's input.

TIP
The Validating event fires only if you move to a control that has CausesValidation set to true. For this reason, it is unusual to have a form where some of the controls have this property set to false and others have it set to true—validation might occur depending on where the user clicks next. Don't do this unless you have a very good reason because it will con- fuse the user and could lead to inconsistent data.

Previous Page
Next Page