Generic Routine for Adding and Removing EventHandler

  • Thread starter Thread starter Derek Hart
  • Start date Start date
D

Derek Hart

I wish to create a routine that can handle removing event handlers. What
type of variable can I pass into the routine (into EventName) to handle
this?

Function HandlerAddRemove(ByVal ctl As Control, ByVal EventName As ??????)
RemoveHandler cboCriteria001.RowSelected, AddressOf EventName
End Function



Derek
 
Derek,
You would need to use the Delegate for the type of event you are adding or
removing. Then when you call the routine you would need to use AddressOf
EventName.

Sub HandlerAddRemove(ByVal ctl As Control, ByVal eventName as
EventHandler)
RemoveHandler ctl.Click, eventName
End Sub

Of course this means you will need overloads for methods that have different
EventHandlers.

Sub HandlerAddRemove(ByVal ctl As Control, ByVal eventName As
MouseEventHandler)
RemoveHandler ctl.MouseMove, eventName
End sub

Then you would call them as:
HandlerAddRemove ctl, AddressOf HandleClick
HandlerAddRemove ctl, AddressOf HandleMouseMove

You could pass eventName as a String do something with Reflection, but then
you are introducing a great potential for runtime errors, which may be more
trouble then its worth.

You can turn Option Strict Off and use eventName As Delegate, however you
are again introducing a great potential for runtime errors, which may be
more trouble than its worth.

Hope this helps
Jay
 
Back
Top