Create and display a form based on its Name

This sample uses Reflection to create a form using only the name stored in a string. While the technology can do way more than what is presented in this example, this will give you a basic start. Note that in this example, an instance of Form2 is created and shown based only on the string "Form2" when the main form is clicked on.

Option Strict On
Option
 Explicit On

Imports
 System
Imports System.Windows.Forms
Imports System.Drawing

Public Class Form1
    
Inherits Form

    
Public Sub New()
        
Me.Text = "Main Form"
        AddHandler Me.Click, AddressOf FormClick
    
End Sub

    Public Sub FormClick(byval sender As Objectbyval e As Eventargs)
        
Dim myType As Type = Type.GetType("Form2")
        
Dim myForm As Form

        
Dim newForm As Object = Activator.CreateInstance(myType)
        myForm = 
CType(newForm, Form)
        myForm.Show()
    
End Sub

    <STAThread()> _
    
Shared Sub Main()
        Application.Run(
New Form1())
    
End Sub
End
 Class

Public
 Class Form2
    
Inherits Form

    
Public Sub New()
        
Me.Text = "Second Form"
    End Sub
End
 Class

1 Comment

  • Hi, i have a solution with several projects, and all my forms have a new constructor.



    How can i pass parameters to my new constructor?







    Thanks,

    Ribeiro Santos

    (arsantos@pexinxa.com)

Comments have been disabled for this content.