Multiple event handlers for the same event in VB.NET

I wrote two event handlers for the TextBox.Leave event for TextBox1

The reason for this is that the first handler is common for several TextBox.Leave events that check the values, and the second for the above TextBox1 , which performs some calculation of the values.

My request is that I can find out which of the two handlers will be executed first when TextBox1.Leave happens?

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

thanks

+4
source share
2 answers

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

Here is a simple example that demonstrates the order determined by the order in which AddHandler is AddHandler :

 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 
+11
source

I would recommend that you go to one handler and determine which text field remains:

 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 
+2
source

Source: https://habr.com/ru/post/1436206/


All Articles