TextBox1.TextChanged事件显示两次MsgBox

时间:2017-04-07 12:44:46

标签: vb.net textbox

我遇到TextBox1.TextChanged事件的问题。 我的代码:

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

问题是MsgBox显示两次,但我想只显示一次并清除TextBox。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分: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