Validation down the Control Hierarchy

As mentioned earlier, the Validate method performs validation on the currently focused control and each of its ancestors. However, a more common need is to validate all of the controls on the form in response to some event, such as the user pressing a Save or Submit button. In .NET 2.0 this becomes extremely easy, and you have a number of options to control the scope of what happens as part of the validation process.

If you want to perform validation for all the controls on a form, or a subset based on some common attributes, you can call the ValidateChildren method of the ContainerControl class. The Form, UserControl, and several other classes derive fromContainerControl, so they inherit this validation functionality. There are two overloads of the ValidateChildren method, one with no argument and one with a ValidationConstraints enumeration value (seeTable 10.4).

Table 10.4. ValidationConstraints Enumeration Values




Validates all controls within the container (including child controls of other containers).


Validates only controls that have a control style of selectable (ControlStyles.Selectable = true). This is the default behavior when ValidateChildren is called with no arguments.


Validates only controls that are enabled.


Validates only controls that are currently visible (Visible = true).


Validates only controls that are set as a tab stop (TabStop = true), meaning that they can be navigated to with the Tab key.


Validates only the immediate children of the container. If any children are themselves container controls, their children won't be validated (no recursion).

The ValidationConstraints enumeration is a flags enumeration, which means its values can be combined with Boolean operators. So if you want to validate all child controls on a form that are selectable, visible, and tab stops, you would call ValidateChildren like this:

ValidateChildren(ValidationConstraints.Selectable | ValidationConstraints.Visible | ValidationConstraints.TabStop);


+1 0

Post a comment