2017-04-07 50 views
0

我有TextBox1.TextChanged事件的問題。 我的代碼:TextBox1.TextChanged事件顯示MsgBox兩次

Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged 
    MsgBox("txt was changed") 
    TextBox1.Clear() 
End Sub 

的問題是,MSGBOX顯示兩次,但是我想表明它只是一個時間和清除文本框。我怎樣才能做到這一點?

+0

清除觸發器再次呼叫您的事件處理程序 – Steve

+0

是的我知道臨時但我想清理文本框並只顯示一次msgbox,我可以這樣做嗎? –

回答

4

兩種方式:

暫時移除處理程序,以防止事件再次射擊:

Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged 
    MsgBox("txt was changed") 
    RemoveHandler TextBox1.TextChanged, AddressOf TextBox1_TextChanged 
    TextBox1.Clear() 
    AddHandler TextBox1.TextChanged, AddressOf TextBox1_TextChanged 
End Sub 

創建一個字段,檢查如果事件是從自身起源:

Dim textBoxAlreadyChanging As boolean = False 

Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged 
    If Not textBoxAlreadyChanging Then 
     MsgBox("txt was changed") 
     textBoxAlreadyChanging = True 
     TextBox1.Clear() 
     textBoxAlreadyChanging = False 
    End If 
End Sub 
+0

非常感謝它的工作:D –

+0

出於興趣,您使用了哪一個? –

+0

第一種方法是完美的,然後第二種,謝謝egain:D –