views:

741

answers:

3

Hi All,

I'm currently in the process of writing a wizard and want to make each page validate before moving onto the next page.

I want to prevent the user from progressing by calling the Validate() method on every child control on the page and and stopping navigation if any of them fail.

The problem is that the Validate() method on every child control is a private method so I can't access it directly. Can anyone give me some advice on how to get a result from the Validate() method on a TextBox (For example) using Reflection?

Many thanks!

Edit: Sorry - should have specified, this is Windows Forms, .Net 2.0

+1  A: 

If you are talking asp.net you can set the ValidationGroup attribute on the control then call this.Validate("GroupName") on the page for the group you need to validate.

Forget the group and just call Validate() if you need to validate the whole page.

Jamey McElveen
+1  A: 

If the pages happen to be ContainerControl instances, you can just call ValidateChildren. If not, this seems to work on an individual control:

private void ValidateControl(Control control)
{
  Type type = control.GetType();
  type.InvokeMember("PerformControlValidation", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.InvokeMethod, null, control, new object[] { true });
}
Eric Smith
A: 

No need for reflection - what you want is ContainerControl.ValidateChildren() (call it on your form/dialog)

Note that ContainerControl.Validate() will only validate the last control to have focus and its ancestors:

The Validate method validates the last child control that is not validated and its ancestors up through, but not including, the current container control

However, if your parent control is not a ContainerControl (Say, a Panel), reflection is indeed necessary - see NoBugz's answer here

ohadsc