Multiple event handlers for the same event in VB.N

2020-02-12 10:09发布

问题:

I've written two event handlers for the TextBox.Leave event for a TextBox1

The reason for this is that the first handler is a common one for multiple TextBox.Leave events which validates the values, and the second one is specific for the above TextBox1 which does some calculation of values.

My query is that can I know which of the two handlers will execute first when TextBox1.Leave happens?

(I know I can remove the code from the common handler to the specific one for TextBox1, but still I wish to know if there is a way.)

Thanks

回答1:

As long as the event handlers are added using the AddHandler statement, the event handlers are guaranteed to be called in the same order that they were added. If, on the other hand, you are using the Handles modifier on the event handler methods, I don't think there is any way to be sure what the order will be.

Here's a simple example that demonstrates the order as determined by the order in which AddHandler is called:

Public Class FormVb1
    Public Class Test
        Public Event TestEvent()

        Public Sub RaiseTest()
            RaiseEvent TestEvent()
        End Sub
    End Class

    Private _myTest As New Test()

    Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        AddHandler _myTest.TestEvent, AddressOf Handler1
        AddHandler _myTest.TestEvent, AddressOf Handler2
        _myTest.RaiseTest()
        RemoveHandler _myTest.TestEvent, AddressOf Handler1
        RemoveHandler _myTest.TestEvent, AddressOf Handler2
    End Sub

    Private Sub Handler1()
        MessageBox.Show("Called first")
    End Sub

    Private Sub Handler2()
        MessageBox.Show("Called second")
    End Sub
End Class


回答2:

I'd recommend you change to having a single handler, and detect which textbox is being left:

Private Sub txt_Leave(sender As Object, e As System.EventArgs) Handles TextBox1.Leave, TextBox2.Leave
  Dim txt As TextBox = DirectCast(sender, TextBox)
  If txt Is TextBox1 Then
    txt.Text = "Very important textbox!"
  Else
    txt.Text = "Boring textbox ho hum."
  End If
End Sub