Answered Form object from text


New member
Dec 1, 2019
Programming Experience
Dim frm as new MyForm

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

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

Any suggestions really appreciated


VB.NET Forum Moderator
Staff member
Aug 17, 2004
Sydney, Australia
Programming Experience
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:
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)

    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.
Top Bottom