VB.NET Forms access via Form Name at Runtime

I

Ian

Hi,

If I have created several forms in my VB.NET app called Form1, Form2, Form3
etc can I instantiate a form via its name.

So if I enter the form's name in a textbox can I have that form appear?

Thanks
Ian
 
H

Herfried K. Wagner [MVP]

* "Ian said:
If I have created several forms in my VB.NET app called Form1, Form2, Form3
etc can I instantiate a form via its name.

So if I enter the form's name in a textbox can I have that form appear?

\\\
Dim objNewForm As Object = _
Activator.CreateInstance( _
Type.GetType("MyApplication.SampleForm") _
)
Dim frm As Form = DirectCast(objNewForm, Form)
frm.Show()
///
 
S

Steven Smith

You could do this sort of thing...

\\\
Private Sub textbox_Leave(ByVal sender As Object, ByVal e
As System.EventArgs) _
Handles txtTextbox.LostFocus

If txtTextbox.text = "form1" Then
Dim objForm1 As New frmForm1
Me.frm1.showdialog()

ElseIf txtTextbox.text = "form2" Then
Dim objForm2 As New frmForm2
Me.frm2.showdialog()
End If
///

obviously you don't have to use LostFocus but can instead
use an other of the textboxes methods to trigger the event
 
A

Armin Zingler

Ian said:
If I have created several forms in my VB.NET app called Form1, Form2,
Form3 etc can I instantiate a form via its name.

So if I enter the form's name in a textbox can I have that form
appear?

It is possible but I think the user is not interested in the names the
developer has chosen as the class name of a form.

If you really need it, have a look at Activator.Createinstance.
 
H

Herfried K. Wagner [MVP]

Hi Steven,

* "Steven Smith said:
\\\
Private Sub textbox_Leave(ByVal sender As Object, ByVal e
As System.EventArgs) _
Handles txtTextbox.LostFocus

If txtTextbox.text = "form1" Then
Dim objForm1 As New frmForm1
Me.frm1.showdialog()
^^^^^^^

.... should read 'objForm1'.
ElseIf txtTextbox.text = "form2" Then
Dim objForm2 As New frmForm2
Me.frm2.showdialog()
End If
///

Little note:

You can 'save' a variable:

\\\
Dim f As Form
Select Case txtTextBox.Text
Case "Form1"
f = New Form1()
Case "Form2"
f = New Form2()
Case ...
...
...
End Select
f.ShowDialog()
///
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top