我了解验证事件如何与文本框一起使用,但我不明白它是如何通过表单上的按钮触发的。
MSDN 没有在他们的文档中列出验证/验证。
但是,这两个属性都列为属性窗口中的事件。
您正在访问错误的 MSDN 文档页面。您应该通过Button Events,在那里您可以找到有关Validated和Validating事件的帮助。
每个
Control
派生对象都有两个名为Validating
和 的事件Validated
。它还有一个名为CausesValidation
. 当它设置为 true(默认为 true)时,控件将参与验证。否则,它不会。
例子:
private void textBox1_Validating(object sender,
System.ComponentModel.CancelEventArgs e)
{
string errorMsg;
if(!ValidEmailAddress(textBox1.Text, out errorMsg))
{
// Cancel the event and select the text to be corrected by the user.
e.Cancel = true;
textBox1.Select(0, textBox1.Text.Length);
// Set the ErrorProvider error with the text to display.
this.errorProvider1.SetError(textBox1, errorMsg);
}
}
private void textBox1_Validated(object sender, System.EventArgs e)
{
// If all conditions have been met, clear the ErrorProvider of errors.
errorProvider1.SetError(textBox1, "");
}
public bool ValidEmailAddress(string emailAddress, out string errorMessage)
{
// Confirm that the e-mail address string is not empty.
if(emailAddress.Length == 0)
{
errorMessage = "e-mail address is required.";
return false;
}
// Confirm that there is an "@" and a "." in the e-mail address, and in the correct order.
if(emailAddress.IndexOf("@") > -1)
{
if(emailAddress.IndexOf(".", emailAddress.IndexOf("@") ) > emailAddress.IndexOf("@") )
{
errorMessage = "";
return true;
}
}
errorMessage = "e-mail address must be valid e-mail address format.\n" +
"For example 'someone@example.com' ";
return false;
}
编辑:
来源:
WinForms 上验证的最大问题是仅当控件“失去焦点”时才执行验证。因此,用户必须在文本框内实际单击,然后单击其他地方才能执行验证例程。如果您只关心输入的数据是否正确,这很好。但是,如果您试图确保用户不会通过跳过文本框而将其留空,则此方法效果不佳。
在我的解决方案中,当用户单击表单的提交按钮时,我会检查表单上的每个控件(或指定的任何容器)并使用反射来确定是否为控件定义了验证方法。如果是,则执行验证方法。如果任何验证失败,则例程返回失败并允许进程停止。此解决方案效果很好,特别是如果您有多个要验证的表单。
参考:
WinForm UI Validation
C# Validating input for textbox on winforms
如果不满足您的条件,您可以使用验证事件取消按钮的操作,而不是将该操作放在 onClick 事件中,而是将其放在验证事件中。
它们被列在那里是因为它们是从Control
类继承的。这里是Validated,这里是Validating。请注意,它们来自Control
.