How to use reflection to open a form


Author
Message
Greg McGuffey
Greg McGuffey
Strategic Support Team Member (4.8K reputation)
Group: Forum Members
Posts: 2K, Visits: 6.6K
My brain hurts a lot trying to figure this out. I would like to be able to have a property that defines the type of a form that I will open. I think I have that down:



Property ProjectSelectorType as System.Type

...

End Property



I can set the property with code like (UserContext is a static class, containing the ProjectSelectorType):



UserContext.ProjectSelectorType = GetType(myApp.ProjectSelectorForm)



So far so good. Now I need to open it. I tried this, which didn't work:



Dim frm As Object = Activator.CreateInstance(UserContext.ProjectSelectorType)

Dim mdiParentInfo As System.Reflection.PropertyInfo = UserContext.ProjectSelectorType.GetProperty("MdiParent")

mdiParentInfo.SetValue(frm, MicroFour.StrataFrame.Application.StrataFrameApplication.MainForm, Nothing)



' The next line throws an exception, my guess because Show() has two overloads

Dim showInfo As System.Reflection.MethodInfo = UserContext.ProjectSelectorType.GetMethod("Show")

showInfo.Invoke(frm)



As mentioned, it doesn't like the GetMethod("Show") call.



What am I doing wrong here? Is there a better way to do this?



I also tried interfaces, but I needed to pass an instance of the form implementing the interface. I don't want the form to be instantiated all the time, just when it's needed.



Thanks!



Reply
Trent Taylor
Trent Taylor
StrataFrame Developer (14K reputation)StrataFrame Developer (14K reputation)StrataFrame Developer (14K reputation)StrataFrame Developer (14K reputation)StrataFrame Developer (14K reputation)StrataFrame Developer (14K reputation)StrataFrame Developer (14K reputation)StrataFrame Developer (14K reputation)StrataFrame Developer (14K reputation)
Group: StrataFrame Developers
Posts: 6.6K, Visits: 7K
How do you handle constructor parameters? I.e. I would normally do this:

The Activator.CreateInstance supports parameters.  It accepts a ParamArray and will pass these to the constructor of the object being created.  You can create an overload on the LaunchForm method that accepts parms as well:

   

Private Sub LaunchForm(ByVal FormType As System.Type, ByVal ParamArray Parms() As Object)
        Activator.CreateInstance(FormType, Parms)
    End Sub

GO

Merge Selected

Merge into selected topic...



Merge into merge target...



Merge into a specific topic ID...





Similar Topics

Reading This Topic

Login

Explore
Messages
Mentions
Search