gpt4 book ai didi

c# - 如何在 Button 类中使用 Validating/Validated 事件?

转载 作者:太空宇宙 更新时间:2023-11-03 18:35:41 26 4
gpt4 key购买 nike

我了解验证事件如何与文本框一起使用,但我不了解它是如何通过表单上的按钮触发的。

MSDN 没有在其 documentation 中列出验证/验证.

但是,这两个属性都列为属性窗口中的事件。 enter image description here

最佳答案

您正在访问错误的 MSDN 文档页面。你应该通过Button Events , 在那里你可以找到关于 Validated 的帮助和 Validating事件。

Each Control-derived object has two events named Validating and Validated. Also it has a property called CausesValidation. When this is set to true (it is true by default) then the control participates in validation. Otherwise, it does not.

例子:

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;
}

编辑:
Source:

The biggest problem with validation on WinForms is the validation is only executed when the control has "lost focus". So the user has to actually click inside a text box then click somewhere else for the validation routine to execute. This is fine if your only concerned about the data that is entered being correct. But this doesn't work well if you're trying to make sure a user didn't leave a textbox empty by skipping over it.

In my solution, when the user clicks the submit button for a form, I check each control on the form (or whatever container is specified) and use reflection to determine if a validating method is defined for the control. If it is, the validation method is executed. If any of the validations fail, the routine returns a failure and allows the process to stop. This solution works well especially if you have several forms to validate.

引用资料:
WinForm UI Validation
C# Validating input for textbox on winforms

关于c# - 如何在 Button 类中使用 Validating/Validated 事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15950227/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com