Generic Routine for Adding and Removing EventHandler

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
 
J

Jay B. Harlow [MVP - Outlook]

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top