防止在自定义文本框中触发验证/验证事件 - vb.net

时间:2009-10-28 20:06:13

标签: vb.net events validating

我有一个自定义文本框组件(继承自system.windows.forms.textbox),我在vb.net(2005)中创建了该组件来处理数字数据的输入。效果很好。

如果数字未更改,我想禁止触发验证和验证的事件。如果用户通过文本框中的表单和选项卡进行制表,则会触发验证/验证事件。

我在想,文本框可以缓存该值并将其与text属性中列出的值进行比较。如果它们不同,那么我希望激活验证/验证事件。如果它们是相同的,则不会被解雇。

我似乎无法弄清楚如何压制事件。我试过覆盖OnValidating事件。那没用。

任何想法?

更新

这是自定义文本框类。我的想法是我想在validate事件上缓存文本框的值。缓存该值后,下次用户选中该框时,验证事件将检查_Cache是​​否与.Text不同。如果是这样的话,我想将验证事件提交到父表单(以及验证事件)。如果_cache是​​相同的,那么我不想将事件提升到表单。本质上,文本框与常规文本框的工作方式相同,只是验证和验证的方法仅在文本更改时才会提升到表单。

 Public Class CustomTextBox

#Region "Class Level Variables"
    Private _FirstClickCompleted As Boolean = False 'used to indicate that all of the text should be highlighted when the user box is clicked - only when the control has had focus shifted to it
    Private _CachedValue As String = String.Empty
#End Region

#Region "Overridden methods"
    Protected Overrides Sub OnClick(ByVal e As System.EventArgs)
        'check to see if the control has recently gained focus, if it has then allow the first click to highlight all of the text
        If Not _FirstClickCompleted Then
            Me.SelectAll() 'select all the text when the user clicks a mouse on it...
            _FirstClickCompleted = True
        End If

        MyBase.OnClick(e)
    End Sub

    Protected Overrides Sub OnLostFocus(ByVal e As System.EventArgs)
        _FirstClickCompleted = False 'reset the first click flag so that if the user clicks the control again the text will be highlighted

        MyBase.OnLostFocus(e)
    End Sub

    Protected Overrides Sub OnValidating(ByVal e As System.ComponentModel.CancelEventArgs)

        If String.Compare(_CachedValue, Me.Text) <> 0 Then
            MyBase.OnValidating(e)
        End If
    End Sub

    Protected Overrides Sub OnValidated(ByVal e As System.EventArgs)
        _CachedValue = Me.Text
        MyBase.OnValidated(e)
    End Sub
#End Region

End Class

更新2:

感谢xpda,解决方案很简单(这么简单,我不明白:))。将OnValidating和OnValidated替换为(也是一个需要记录状态的布尔值):

Protected Overrides Sub OnValidating(ByVal e As System.ComponentModel.CancelEventArgs)
    If String.Compare(_CachedValue, Me.Text) <> 0 Then
        _ValidatingEventRaised = True
        MyBase.OnValidating(e)
    End If
End Sub

Protected Overrides Sub OnValidated(ByVal e As System.EventArgs)
    If Not _ValidatingEventRaised Then Return

    _CachedValue = Me.Text
    _ValidatingEventRaised = False
    MyBase.OnValidated(e)
End Sub

2 个答案:

答案 0 :(得分:3)

您可以在TextChanged事件中设置一个标志,并使用该标志来判断是否在验证处理程序的开头退出。

答案 1 :(得分:0)

尝试在您的控件中处理事件并取消它,如下所示。

Private Sub TextBox1_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating
    e.Cancel = True
End Sub