Export (0) Print
Expand All

10.5.2 AddHandler and RemoveHandler Statements

Visual Studio .NET 2003

Although most event handlers are automatically hooked up through WithEvents variables, it may be necessary to dynamically add and remove event handlers at run time. AddHandler and RemoveHandler statements do this.

Each statement takes two arguments: the first argument must be an expression that is classified as an event access and the second argument must be an expression that is classified as a value. The second argument's type must be the delegate type associated with the event access. For example:

Imports System

Public Class Form1
    Public Sub New()
        ' Add Button1_Click as an event handler for Button1's Click event.
        AddHandler Button1.Click, AddressOf Button1_Click
    End Sub 

    Private Button1 As Button = New Button()

    Sub Button1_Click(sender As Object, e As EventArgs)
        Console.WriteLine("Button1 was clicked!")
    End Sub

    Public Sub Disconnect()
        RemoveHandler Button1.Click, AddressOf Button1_Click
    End Sub
End Class

Given an event E, the statement calls the relevant add_E or remove_E method on the instance to add or remove the delegate as a handler for the event. Thus, the above code is equivalent to:

Imports System

Public Class Form1
    Public Sub New()
        Button1.add_Click(AddressOf Button1_Click)
    End Sub 

    Private Button1 As Button = New Button()

    Sub Button1_Click(sender As Object, e As EventArgs)
        Console.WriteLine("Button1 was clicked!")
    End Sub

    Public Sub Disconnect()
        Button1.remove_Click(AddressOf Button1_Click)
    End Sub
End Class
AddHandlerStatement ::= 
   AddHandler Expression , Expression StatementTerminator
RemoveHandlerStatement ::=
   RemoveHandler Expression , Expression StatementTerminator

See Also

10.5.1 RaiseEvent Statement | 10.5 Event Statements | AddHandler Statement (Visual Basic Language Reference) | RemoveHandler(Visual Basic Language Reference) | AddHandler and RemoveHandler (Visual Basic Language Concepts)

Show:
© 2014 Microsoft