2009-10-28 93 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