c# - WinForm 用户界面验证

标签 c# .net winforms validation user-interface

我需要在我的 winform 应用程序中实现输入验证。有许多不同的表单可以输入数据,我不想逐个控制地控制表单并为每个项目创建 isValid 等。其他人如何处理这个问题?

我看到大多数相关帖子都涉及 Web 应用程序和/或提及 Enterprise Library Validation Application Block .现在我承认我还没有彻底研究 ELVAB,但它似乎对我需要的东西来说有点矫枉过正。我目前的想法是编写一个具有各种要求的类库,并将控件作为参数传递给它。我已经有一个 RegEx 函数库,用于诸如 isValidZipCode 之类的东西,所以这可能是我开始的地方。

我想要的是一个验证按钮,onClick 循环遍历该表单页面上的所有控件并执行所需的验证。我怎样才能做到这一点?

最佳答案

验证已内置到 WinForms 库中。

每个 Control 派生的对象都有两个名为 ValidatingValidated 的事件。它还有一个名为 CausesValidation 的属性.当此设置为 true(默认情况下为 true)时,控件将参与验证。否则,它不会。

验证是焦点的一部分。当您将焦点从控件上移开时,将触发其验证事件。事实上,焦点事件是按特定顺序触发的。来自 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:

  1. Enter
  2. GotFocus
  3. Leave
  4. Validating
  5. Validated
  6. LostFocus

When you change the focus by using the mouse or by calling the Focus method, focus events occur in the following order:

  1. Enter
  2. GotFocus
  3. LostFocus
  4. Leave
  5. Validating
  6. Validated

If 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.

ContainerControl 也有一个名为 ValidateChildren() 的方法它将遍历包含的控件,并验证它们。

关于c# - WinForm 用户界面验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/769184/

相关文章:

c# - 允许用鼠标滚动但不显示浏览器滚动条?

c# - 用于选择畅销书的 LINQ 查询

c# - 表单在 backgroundworker 中不显示为对话框?

c# - .Net WebException 检查本地机器是否可以访问互联网

c# - 为什么 ListView 会触发事件,指示添加后未选中选中的项目

c# - 将 winform 插件添加到 Word 中的自定义任务 Pane

c# - SQLite 的 DLL hell

android - 在 android 上使用 protobuf 将数据发送到 WCF 服务(使用 protobuf.net)

php - PHP如何用作.NET语言(具体是ASP.NET)?

c# - 服务器 500 : Too many pending secure conversations