我有一個自定義文本框組件(從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
我一開始並不明白你的意思,但現在我想我已經擁有了它,它非常簡單。謝謝! – Bluebill 2009-10-29 13:13:42