I am attempting to launch a specific form depending on the selected node of a treeview on the doubleclick event. The code I need to use to launch the form is a little bulky becuase I have to ensure that the form is not disposed, and that the form is not already open, before launching a new instance. I'd like to have all of this checking happen in one place at the end of the function, which means that I have to be able to pass the right form type to the code at the end. I'm trying to do this with a System.Type, but that doesn't seem to be working. Could someone point me in the right direction, please?
With TreeView.SelectedNode
Dim formType As Type
Select Case .Text
Case "Email to VPs"
formType = EmailForm.GetType()
Case "Revise Replacers"
formType = DedicatedReplacerForm.GetType()
Case "Start Email"
formType = EmailForm.GetType()
End Select
Dim form As formType
Dim form As formType
Try
form = CType(.Tag, formType)
If Not form.IsDisposed Then
form.Activate()
Exit Sub
End If
Catch ex As NullReferenceException
'This will error out the first time it is run as the form has not yet
' been defined.
End Try
form = New formType
form.MdiParent = Me
.Tag = form
CType(TreeView.SelectedNode.Tag, Form).Show()
End With
You can't new
a Type. The Type is a runtime-type information, new
needs to know the type at compile time.
Use either reflection (Activator) or generics.
Sorry I don't know VB, I can't give you a code example in VB.
c# example:
T CreateForm<T>() where T : Form, new()
{
return new T();
}
or
Form CreateForm(Type t)
{
return (Form)Activator.CreateInstance(t);
}