2009-10-28 94 views
3

我有一个自定义文本框组件(从system.windows.forms.textbox继承),我在vb.net(2005)中创建处理输入数字数据。它运作良好。防止自定义文本框中触发验证/验证事件 - vb.net

如果数字没有改变,我想压制验证和验证的事件。如果用户通过文本框中的表单和选项卡切换,将激发验证/验证的事件。

我在想,文本框可以缓存值,并将其与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 

回答

3

您可以在TextChanged事件的标志,并使用该标志告知是否在验证处理程序的开始退出。

+0

我一开始并不明白你的意思,但现在我想我已经拥有了它,它非常简单。谢谢! – Bluebill 2009-10-29 13:13:42

0

试图处理你的控件的事件和下面将其取消。

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

糟糕。对不起,没有注意到你已经尝试覆盖OnValidating事件。 – DevByDefault 2009-10-28 20:15:39

+0

使用e.cancel = true的问题是它表示验证方法失败。它并不妨碍以主要形式提出事件。 – Bluebill 2009-10-29 12:17:43