Opening forms based on form Type

I'm currently trying to create a unified function for opening some forms, but there are some problems when trying to utilize the Types.  

For example, lets say I have 5 forms:  Form1, Form2, etc.

Calling the function, I would like to use:  OpenFunction(GetType(Form1))

A sample of what I've tried is:

    Public Function OpenForm(ByVal FormType As Type)
        Dim frm As New Form

        'Find if a form of that type is already open (found in the Forms Collection).  Returns a reference to the form.
        frm = Forms.FindForm(FormType)

        'If the form is already open, bring it to the front
        If Not frm Is Nothing Then
            frm.BringToFront()
        Else
            'Otherwise, the form is not open, so create a new one
            frm = New ??? 'Here is the problem
        End If

        'Show the form
        frm.Show()
    End Function

Is there any way to create a New form, given the Type?  
LVL 17
ZeonFlashAsked:
Who is Participating?
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
See the Activator.CreateInstance Method (Type) :
http://msdn2.microsoft.com/en-us/library/wccyzw83.aspx

VB.Net 2005 code:

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        OpenForm(Form2.GetType)
    End Sub

    Public Sub OpenForm(ByVal FormType As Type)
        Dim frm As Form
        For Each frm In Application.OpenForms
            If frm.GetType.Equals(FormType) Then
                If frm.WindowState = FormWindowState.Minimized Then
                    frm.WindowState = FormWindowState.Normal
                End If
                frm.Show()
                frm.BringToFront()
                frm.Activate()
                Exit Sub
            End If
        Next

        frm = CType(Activator.CreateInstance(FormType), Form)
        frm.Show()
    End Sub

End Class
0
 
ZeonFlashAuthor Commented:
Works like a charm.  Thanks!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.