窗体上有很多控件,用来设置一些参数,需要在点击OK时对所有的参数进行验证,如果有参数无效则显示错误信息,效果如下:
首先,需要为控件添加验证事件
正常情况下,应该是控件的焦点发生变化时才会触发Validated事件,下面是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:
When you change the focus by using the mouse or by calling the Focus method, focus events occur in the following order:
-
Enter
-
GotFocus
-
LostFocus
-
Leave
-
Validating
-
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.
For more information about handling events, see Consuming Events.
但是由于控件较多,总不能一个一个去改变焦点,而且这么做也有些不合理,有没有简单的方法能够触发这些控件的Validated事件呢?
在网上找了找,发现解决办法其实很简单,Form类提供了一个ValidateChildren方法,使用它就可以轻松地实现上述需求
MSDN上的资料 http://msdn.microsoft.com/en-us/library/ms159409.aspx
This member overrides ContainerControl.ValidateChildren(), and more complete documentation might be available in that topic.
Causes all of the child controls within a control that support validation to validate their data.
Namespace: System.Windows.Forms
Assembly: System.Windows.Forms (in System.Windows.Forms.dll)
Return Value
Type: System.Booleantrue if all of the children validated successfully; otherwise, false. If called from the Validating or Validated event handlers, this method will always return false.
如果不想验证所有的控件,比如有些控件可能Visible属性会随时发生变化,在验证时想跳过这些控件,方法就是在调用ValidateChildren时传递参数进行限制
public virtual bool ValidateChildren (
ValidationConstraints validationConstraints
)
ValidationConstraints Enumeration Members
Member name | Description | |
---|---|---|
Enabled | Validates child controls whose Enabled property is set to true. | |
ImmediateChildren | Validates child controls that are directly hosted within the container. Does not validate any of the children of these children. For example, if you have a Form that contains a custom UserControl, and the UserControl contains a Button, using ImmediateChildren will cause the Validating event of the UserControl to occur, but not the Validating event of the Button. | |
None | Validates all child controls, and all children of these child controls, regardless of their property settings. | |
Selectable | Validates child controls that can be selected. | |
TabStop | Validates child controls that have a TabStop value set, which means that the user can navigate to the control using the TAB key. | |
Visible | Validates child controls whose Visible property is set to true. |