Search code examples
vb.neteventshandlereventhandleraddhandler

Add EventHandler to object of unknown type?


We're creating objects at runtime so before running the code doesn't know what object it is working with. We want to add an event handler to every TextBox which is created at runtime. But when we try AddHandler obj.Leave, AddressOf leaveControl the compiler won't run the program because "object doesn't have an event like Leave".

Is there a way to add an event handler to a object of unknown type?

Thanks :)


Solution

  • VB.NET supports late binding to write dynamic code. That works well for properties and methods but not for events. Odd restriction, I don't know the technical reason for it. Short from it never having to be necessary in earlier versions of Basic where event binding was dynamic based on the method name, I suspect it has something to do with the WithEvents keyword.

    The workaround is simple enough, you need to use Reflection. Like this:

        Dim obj As Object = New TextBox
        Dim evt = obj.GetType().GetEvent("Leave")
        evt.AddEventHandler(obj, New EventHandler(AddressOf leaveControl))