Handling Multiple Events

The Handles keyword offers even more flexibility. Not only can the method name be anything you choose, a single method can handle multiple events if you desire. Again, the only requirement is that the method and all the events being raised must have the same parameter list.

This explains why all the standard events raised by the .NETsystem class library have exactly two parameters — the sender and an EventArgs object. Being so generic makes it possible to write very generic and powerful event handlers that can accept virtually any event raised by the class library.

One common scenario where this is useful is when you have multiple instances of an object that raises events, such as two buttons on a form:

Private Sub MyClickMethod(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles Button1.Click, Button2.Click

End Sub

Notice that the Handles clause has been modified so that it has a comma-separated list of events to handle. Either event will cause the method to run, providing a central location for handling these events.

0 0

Post a comment