2008-09-05

Load form from its String name

In some situations we need to load form from its string name. Lets consider for example, you have stored the list of forms in your application in a database and now you want to load those forms at run-time. The simplest solution for this is that you will write if conditions like this:

' Dummy code
Dim formName As String

formName = "form1" ' Get the form name from database.

If formName = "form1" Then
Dim frm1 As New Form1
frm1.Show()
ElseIf formName = "form2" Then
Dim frm2 As New Form2
frm2.Show()
ElseIf formName = "form3" Then
Dim frm3 As New Form3
frm3.Show()
ElseIf formName = "form4" Then
Dim frm4 As New Form4
frm4.Show()
End If
But what if you have 40 more forms in your application. So basically writing that much if conditions is not a good solution. To accomplish the goal we need to use Reflection. Here is the code:

Imports System.Reflection

Public Class Form2

Private Sub Button1_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs _
) Handles Button1.Click

Dim frm As New Form
Dim formName As String = "Form1"

formName = Me.GetType.Assembly.GetName.Name & "." & formName
frm = DirectCast(Me.GetType.Assembly.CreateInstance(formName), Form)
frm.Show()
End Sub

End Class

No comments: