Raising events from dynamic forms through reflection

I have been using reflection for a while to open up forms dynamically and have been past the form properties and form methods hurdle for quite some time. I just had to raise an event from my form that is being loaded dynamically. A quick article by Dino Esposito on VB2theMax made it relatively easy to add this little bit of functionality into my .net quiver. Since I am doing it a bit differently (using a form, rather than a class) here is how I did it. This isn’t my exact code, since I have stripped out some other trickery that I don’t want to get in the way of what I am trying to show here.

Dim asmAssemblyContainingForm As [Assembly] = [Assembly].LoadFrom(“AssemblyContainingForm.DLL“)

Dim TypeToLoad As Type = asmAssemblyContainingForm.GetType(“assemblynamespace.formclassName”)

Dim GenericInstance As Object

GenericInstance = Activator.CreateInstance(TypeToLoad)

Dim f As Form = CType(GenericInstance, Form)

‘//here is the event setup

Dim frmEventUpdateTree As System.Reflection.EventInfo

‘//“TreeSourceChanged“ is the name of the event being raised from my form

frmEventUpdateTree = TypeToLoad.GetEvent(“TreeSourceChanged”)

‘//create a delegate of the same type as my raised event to a local method  named “SetGetNewTreeTrue“

Dim frmDel As [Delegate] = [Delegate].CreateDelegate(frmEventUpdateTree.EventHandlerType, Me, “SetGetNewTreeTrue”)

‘//link up my delegate to the dynamic form

frmEventUpdateTree.AddEventHandler(f, frmDel)

  Sign up for my newsletter so you don't miss my conference & Pluralsight course announcements!  

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.

This site uses Akismet to reduce spam. Learn how your comment data is processed.