Resolved Remove Click Event Handler

aaaron

Well-known member
Joined
Jan 23, 2011
Messages
216
Programming Experience
10+
I want to be able to remove an event handler from a component. I tried a couple of things includeing the code below but can't get it to work.

Or maybe it is working but my checking is faulty.

VB.NET:
 Private mDelegateSaveBitmap As New System.EventHandler(AddressOf Me.ToolStripMenuItem_General0_DateOfSelected0_Click)
 Private Sub RemoveHandlerTest()
     RemoveClickHandler(ToolStripMenuItem_General0_DateOfSelected0, "Click", mDelegateSaveBitmap) 
 End Sub
 Public Shared Sub RemoveClickHandler(target As Object, eventName As String, handler As [Delegate])
     Dim eventInfo As EventInfo = target.GetType().GetEvent(eventName, BindingFlags.Instance Or BindingFlags.Public)
     If eventInfo IsNot Nothing Then
         Dim removeMethod As MethodInfo = eventInfo.GetRemoveMethod()
         If removeMethod IsNot Nothing Then
             removeMethod.Invoke(target, {handler})
         Else
             Console.WriteLine($"The event '{eventName}' does not have a remove method.")
         End If
     Else
         Console.WriteLine($"The event '{eventName}' was not found.")
     End If
 End Sub
 
Solution
You absolutely should not be trying to directly remove an event handler that's attached via a Handles clause. Just assign something else, including Nothing, to the field and the events of the original object will not be handled any more. Handles clauses associate a handler with a field rather than an object.
You absolutely should not be trying to directly remove an event handler that's attached via a Handles clause. Just assign something else, including Nothing, to the field and the events of the original object will not be handled any more. Handles clauses associate a handler with a field rather than an object.
 
Solution
It's ok to remove if Addhandler was used?

EDIT: Added
I just found the RemoveHandler statment - So it's OK to remove.

Thanks
 
Last edited:
Back
Top