Sometimes it is impossible or undesirable to handle events declaratively . For example, Shared events cannot be handled declaratively, because no field can be declared using the WithEvents keyword. Or a class may wish to handle a particular event for only a short period of time without adding the overhead of creating a new field. There are two statements, AddHandler and RemoveHandler , that allow a program to dynamically start and stop handling events.
The AddHandler and RemoveHandler statements each take two operands: an event and an event handler. The first operand, the event, specifies the event to be handled and the instance that will raise it; the statements do not require a WithEvents variable, so they are more flexible than declarative event handling. The event handler is specified by putting the keyword AddressOf in front of the name of the handler. (The meaning and use of AddressOf is explained in more detail later in the chapter.) For example, AddHandler and RemoveHandler can be used as follows .
Class Form1 Public Buttons As ArrayList = New ArrayList() Public Sub CreateButton() Dim NewButton As Button = New Button() AddHandler NewButton.Click, AddressOf Me.Button_Click Buttons.Add(NewButton) End Sub Public Sub DeleteAllButtons() For Each Button As Button in Buttons RemoveHandler Button.Click, AddressOf Me.Button_Click Next Button Buttons.Clear() End Sub Public Sub Button_Click() MsgBox("Button1 was clicked!") End Sub End Class
In this example, the method CreateButton dynamically creates a button on the form. Since CreateButton can create an arbitrary number of buttons on the form, there is no way to know how many WithEvents fields you might need (and adding a Handles clause for all of them would be unwieldy!). Instead, when a new button is created, CreateButton dynamically hooks up the Button_Click method to the Click event of the new button. When DeleteAllButtons goes to destroy all the buttons, it is important to stop listening to Click events from the buttons. The RemoveHandler statement removes the class from the list of those handling the button's Click event.
Remember that RemoveHandler only removes the handler for the particular instance that qualifies the event handler. If two instances of Form1 were handling the Click event on the same button, a RemoveHandler statement could remove only one of the two handlers at a time.