WinForm UI Validation

Validation is already built into the WinForms library.

Each Control-derived object has two events named Validating and Validated. Also it has a property called CausesValidation. When this is set to true (it is true by default) then the control participates in validation. Otherwise, it does not.

Validation occurs as part of focus. When you focus off of a control, its validation events are fired. In fact the focus events are fired in a specific order. From MSDN:

When you change the focus by using the
keyboard (TAB, SHIFT+TAB, and so on),
by calling the Select or
SelectNextControl methods, or by
setting the
ContainerControl..::.ActiveControl
property to the current form, focus
events occur in the following order:

  1. Enter
  2. GotFocus
  3. Leave
  4. Validating
  5. Validated
  6. LostFocus

When you change the focus by using the
mouse or by calling the Focus method,
focus events occur in the following
order:

  1. Enter
  2. GotFocus
  3. LostFocus
  4. Leave
  5. Validating
  6. Validated

If the CausesValidation property is
set to false, the Validating and
Validated events are suppressed.

If the Cancel property of the
CancelEventArgs is set to true in the
Validating event delegate, all events
that would usually occur after the
Validating event are suppressed.

Also a ContainerControl has a method called ValidateChildren() which will loop through contained controls, and validate them.

Leave a Comment