As a follow up to my previous post about enhancing the validation controls within Windows Forms, there might be times when you would like to manually invoke the “Validating” event of a control.
For example, you might want to have a routine that fires on the form's “Closing” event or a data save method to loop through all the controls on your form and validate them independently to ensure that all controls are valid. This might be a common scenario in data entry forms where you might create a new record and the user might not touch all the fields on your form (and thus never trigger the “Validating” event of your controls).
There are two different solutions to this problem. One, pointed out by Chris Sells (read more), invokes the Control's “NotifyValidating” event through Reflection. Here is an example:
protected bool IsControlValid(Control controlToValidate)
{
Debug.Assert(controlToValidate != null, "Control to validate is null");
Type t = typeof(Control);
MethodInfo mi = t.GetMethod("NotifyValidating", BindingFlags.Instance |
BindingFlags.NonPublic);
Debug.Assert(mi != null, "Could not get method information.");
if(((Boolean)mi.Invoke(controlToValidate, null)))
return false;
else
return true;
}
You can also trigger the Validation event by giving focus to a control and taking the focus away. You might even loop through all the controls on your form and focus each of them individually (or an individual control by giving it focus then changing the focus to another control), achieving the same effect:
protected void ValidateForm
{
for(int i = 0; i < this.Controls.Count; i++)
this.Controls
.Focus();
}
Which solution is better? I'd recommend staying away from reflecting on the internal methods and properties of Framework classes. This will future proof your code as much as possible and prepare you for any breaking changes down the road to the internals of the Framework.
Technorati Tags: windows forms, validation
Posted
04-12-2004 7:46 AM
by
paul.laudeman