我想在将文本保存到数据库之前检查用户在文本框中写的内容。做这个的最好方式是什么?我想我总能写一些 ifs 或一些 try-catch block ,但我想知道是否有更好的方法。我读过一些关于验证事件的内容,但我不确定如何使用它们。
最佳答案
描述
验证文本框的方法有很多种。您可以在每次击键时、稍后或在 Validating
事件中执行此操作。
如果您的 TextBox 失去焦点,则会触发 Validating
事件。例如,当用户单击另一个控件时。如果您设置 e.Cancel = true
,TextBox 不会失去焦点。
MSDN - Control.Validating Event 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
Enter
GotFocus
Leave
Validating
Validated
LostFocus
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
示例验证事件
private void textBox1_Validating(object sender, CancelEventArgs e)
{
if (textBox1.Text != "something")
e.Cancel = true;
}
更新
您可以使用 ErrorProvider
可视化您的 TextBox 无效。
查看Using Error Provider Control in Windows Forms and C#
更多信息
关于C# 在 winforms 上验证文本框的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8915151/