Answered Form object from text

ChrisJ

New member
Joined
Dec 1, 2019
Messages
2
Programming Experience
10+
Dim frm as new MyForm
frm.show()

MyForm is one of many forms in the application.
I am trying to use a database text field which contains the name of the form

Something like...

dim sForm as string = "frmTest"
Dim frm as new sForm
frm.show()

I know this won't work, but the correct syntax eludes me

Any suggestions really appreciated
 

jmcilhinney

VB.NET Forum Moderator
Staff member
Joined
Aug 17, 2004
Messages
14,148
Location
Sydney, Australia
Programming Experience
10+
There is no correct syntax. What you're suggesting is not really possible. It is to a degree but, if you don't know the type when you write the code, you can't write code specific to that type. If you know that it will definitely be a type that inherits Form then you can write code to that type, which may be enough. Here's an example using Reflection:
VB.NET:
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim typeName = "WindowsApp1.Form2"
        Dim formType = Type.GetType(typeName)
        Dim constructor = formType.GetConstructor({})
        Dim form = DirectCast(constructor.Invoke({}), Form)

        form.Show()
    End Sub

End Class
You need the fully qualified name of the type, i.e. namespace and class name. You can then get a Type object representing that type. From that, you can get a ConstructorInfo representing the type's parameterless constructor - it needs to have such a constructor or you'll have to figure out which one to invoke - and invoke that to get an instance. As you know that the type inherits Form but nothing more, you can cast as that type, which gives you access to the Show method. Nothing that doesn't come from that type will be accessible though, without further Reflection.
 

ChrisJ

New member
Joined
Dec 1, 2019
Messages
2
Programming Experience
10+
Perfect thanks.
Yes in this case it will always inherit from Form
tested and works
 
Top Bottom