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
Answer. By passing an anonymous function, or a named function, with multiple event handler calls as the function body, to our event listener (like onClick , onKeyUp , onChange , etc) we can call multiple event handlers in response to a single event.
Can you add multiple event listeners to a button? We can add multiple event listeners for different events on the same element. One will not replace or overwrite another. In the example above we add two extra events to the 'button' element, mouseover and mouseout.
To connect multiple events to a single event handler in C#Click the name of the event that you want to handle. In the value section next to the event name, click the drop-down button to display a list of existing event handlers that match the method signature of the event you want to handle.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With