Iteration in the control is simple if you use recursion:
delegate bool Validator(Control control);
static bool Validate(Control control, Validator validator) {
bool isValid = validator(control);
foreach (Control child in control.Controls)
isValid = isValid && Validate(child, validator);
return isValid;
}
Consider you have the implementation of
Validator
, a delegate instance capable of doing validation for one individual control instance. It does not have to be a static delegate instance, because it may need access to some instance like a form. The recursive method will iterate all controls. You can add additional parameters to the delegate, to pass data or something.
One problem of this approach is that the validator is agnostic to the
run-time type of the control, so, you would need to do the dynamic cast via the
as
operator and do different validation for different control type. This is a certain abuse of "pure" OOP. As there are pieces of programming where such things are unavoidable, I provided some very general solution it it. Please see my CodeProject article:
Dynamic Method Dispatcher[
^].
Another solution is more regular OOP. Subclass all of your control classes to implement some common interface, such as
IValidate
and use the interface reference in the validator instead
Control
.
Those are the solutions for Boolean validation.
And finally, you can use
System.Windows.Forms
approach: handle the events
Validating
and
Validated
in all your control; don't forget to set
CausesValidation
. Please see:
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.causesvalidation.aspx[
^],
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.validating.aspx[
^],
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.validated.aspx[
^].
—SA