C# 在 winforms 上验证文本框的输入

标签 c# winforms validation

我想在将文本保存到数据库之前检查用户在文本框中写的内容。做这个的最好方式是什么?我想我总能写一些 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/

相关文章:

c# - 暂时取消订阅事件的巧妙解决方案

.net - 带有窗口窗体应用程序的 ASP.NET

Java - 验证给定的字符串是否代表日期,即 "YYYY-MM-DD"?

c# - 需要一种更好的方法来遍历表单控件

c# - 在 Proto-Buf 中使用 bool 类型

c# - StatusIcon 未出现在通知区域

c# - 从文本框值运行 SQL 命令

validation - 如何在自定义多字段验证器中将其他组件标记为无效

java - 如何在将来引用另一个日期验证该日期?

c# - 多重约束违反 VS 2010/SQL Server/EF 代码优先