Members

Technology Zones

IBM Learning Center

Articles

Hosted By

MaximumASP

Info

Rated
Read 29,087 times

Related Categories

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

James first started writing tutorials on Visual Basic in 1999 whilst starting this website (then known as VB Web). Since then, the site has grown rapidly, and James has written numerous tutorials, articles and reviews on VB, PHP, ASP and C#. In October 2003, James formed the company Developer Fusion Ltd, which owns this website, and also offers various development services. In his spare time, he's a 3rd year undergraduate studying Computer Science in the UK. He's also a Visual Basic MVP.

Comments

  • dynamic forms display

    Posted by f_htn on 28 Oct 2003

    I used a modified version of the dynamic forms display as follows

    Private Sub Command2_Click()
    Dim frm As Form
    Dim selform As String
    pn = pn +1

    selform = "TB-" & pn
    Set frm = Form...