发布网友 发布时间:2022-12-31 07:44
共1个回答
热心网友 时间:2023-11-02 02:24
窗体上有很多控件,用来设置一些参数,需要在点击OK时对所有的参数进行验证,如果有参数无效则显示错误信息,效果如下: 首先,需要为控件添加验证事件private void textBox1_Validated(object sender, EventArgs e) { if (string.IsNullOrEmpty(textBox1.Text)) errorProvider1.SetError(textBox1, "invalid textbox value, could not be null"); else errorProvider1.SetError(textBox1, string.Empty); } private void textBox2_Validated(object sender, EventArgs e) { if (string.IsNullOrEmpty(textBox2.Text)) errorProvider1.SetError(textBox2, "textbox2 invalid"); else errorProvider1.SetError(textBox2, ""); } 正常情况下,应该是控件的焦点发生变化时才会触发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: EnterGotFocusLeaveValidatingValidatedLostFocusWhen you change the focus by using the mouse or by calling the Focus method, focus events occur in the following order: EnterGotFocusLostFocusLeaveValidatingValidatedIf 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事件呢?