devxlogo

AddRemoveEventHandler – Add or remove an event handler through reflection

' Add or remove an event handler through reflection,'  and return True if successful'' Examples:'    ' add an event handler for Button1's Click event'    AddRemoveEventHandler(Button1, "Click", New EventHandler(AddressOf ' OnButton1Click))'    ' remove an event handler for Button1's Click event'    AddRemoveEventHandler(Button1, "Click", New EventHandler(AddressOf ' OnButton1Click), False)Function AddRemoveEventHandler(ByVal obj As Object, ByVal eventName As String, _    ByVal eventHandler As [Delegate]) As Boolean    Return AddRemoveEventHandler(obj, eventName, eventHandler, True)End FunctionFunction AddRemoveEventHandler(ByVal obj As Object, ByVal eventName As String, _    ByVal eventHandler As [Delegate], ByVal addEventHandler As Boolean) As _    Boolean    Dim type As Type = obj.GetType()    ' get the EventInfo object, exit if not found    Dim evInfo As System.Reflection.EventInfo = type.GetEvent(eventName)    If evInfo Is Nothing Then Return False    Try        If addEventHandler Then            evInfo.AddEventHandler(obj, eventHandler)        Else            evInfo.RemoveEventHandler(obj, eventHandler)        End If        Return True    Catch        Return False    End TryEnd Function

Charlie has over a decade of experience in website administration and technology management. As the site admin, he oversees all technical aspects of running a high-traffic online platform, ensuring optimal performance, security, and user experience.

See also  How Engineering Leaders Spot Weak Proposals

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.