How to display Visual Basic forms dynamically

Often you may want to display application forms dynamically. For
instance, you might have a listbox that lists user-friendly form
names. When a user selects a name, you want Visual Basic to display
the associated form.

This type of feature, however, requires the use of a dynamic form name.
After all, you won't know which form the user has selected, as you
would with other pre-defined methods, such as opening a specific form
when the user clicks a button. Fortunately, Visual Basic provides an
easy way to reference a form dynamically with the Forms collection.

This global collection object represents all loaded standard, MDI and
MDI child forms in an application. As with most VB collections, the
Forms object lets you refer to items either by index or by name, as
seen below:

Set frm = Forms(1)

or

Set frm = Forms("frmEditor")

And of course, you can substitute a variable for any of the index
values, like so:

Set frm = Forms(strName)

With this collection available, it becomes a relatively easy matter to
load a form dynamically. The following code shows a simplified way to
do so:

Private Sub Form_Load()
With List1
    .AddItem "Form1"
    .AddItem "Form2"
    .AddItem "Form3"
End With
End Sub

Private Sub List1_Click()
Dim frm As Form
Dim selForm As String
    With List1
        selForm = .List(.ListIndex)
    End With
    Set frm = Forms.Add(selForm)
    frm.Show
    Set frm = Nothing
End Sub

You might also like...

Comments

James Crowley James first started this website when learning Visual Basic back in 1999 whilst studying his GCSEs. The site grew steadily over the years while being run as a hobby - to a regular monthly audience ...

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Beware of bugs in the above code; I have only proved it correct, not tried it.” - Donald Knuth