【问题标题】:Strange Issue Validating Empty Text Box in Winforms .NET 4.0 VB.NET在 Winforms .NET 4.0 VB.NET 中验证空文本框的奇怪问题
【发布时间】:2012-06-21 02:59:16
【问题描述】:

我只是在新的 winform 中添加验证。我将 validatingvalidated 事件与 error provider 控件结合使用。请看下面的代码。

第一次验证没有问题(即如果用户输入超过 12 个字符)。在验证事件中设置错误,并且错误一直存在,直到用户输入 12 个或更少的字符。然后输入 Validated 事件并将错误重置为空字符串。

但是,在同一文本框中进行第二次验证时存在问题。代码检查文本框中的零长度.. 并设置提供程序错误。在调试器中观察,确实调用了这段代码,并且设置了错误。然后发生了一些奇怪的事情,validated 事件被(意外地) 触发,并且那里的代码立即重置了错误。

当已经设置了错误时,为什么会触发 validated 事件?这似乎是一个 .NET 错误。谁能提出另一种方法,或者说我做错了什么?

谢谢,

巴扎

Private Sub SampleCodeTextBox_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles SampleCodeTextBox.Validating
    If SampleCodeTextBox.Text.Length > 12 Then
        e.Cancel = True
        FormErrorProvider.SetError(SampleCodeTextBox, "Max of 12 characters for sample code")
    End If

    If SampleCodeTextBox.Text.Trim.Length = 0 Then
        FormErrorProvider.SetError(SampleCodeTextBox, "Must enter a sample code")
    End If
End Sub

Private Sub SampleCodeTextBox_Validated(sender As Object, e As System.EventArgs) Handles SampleCodeTextBox.Validated
    FormErrorProvider.SetError(SampleCodeTextBox, "")
End Sub

【问题讨论】:

    标签: .net vb.net winforms validation


    【解决方案1】:

    当验证事件处理程序中的零长度文本检查失败时,您需要将CancelEventArgs.Cancel 属性设置为True

    来自Control.Validated Event上的MSDN文章:

    如果 CancelEventArgs 的 Cancel 属性在 验证事件委托,通常在之后发生的所有事件 Validating 事件被抑制。

    【讨论】:

      【解决方案2】:

      你不是在下一个 if 块中错过了e.Cancel = True 吗?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-02-10
        • 1970-01-01
        • 2015-10-12
        • 2017-10-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多