This article originally
appeared in the Visual Basic newsletter. Automatically subscribe to our free Visual Basic newsletter.
In most Visual Basic 6 projects, the number of controls on a
form are set at design time and don’t change when the program runs. But what if
you have a situation where the number of controls needed isn’t known until
runtime? For example, the program could read data from a database and need to
display one control for each record that was found. This tip shows you how to
add controls to a form at runtime. This technique is also applicable to
essentially any Visual Basic control.
To add controls at runtime, there must already be at least
one instance of the control on the form, and it must be part of a control
array. To create a control array containing only a single control, add the
control to the form and then set its Index
property to 0. This control doesn’t have to be visible.
When the program runs, you add additional controls with the
Load statement: Load ControlName(Index).
is the Name property of the control
array you created and Index is the Index property of the new control. You
should start at 1 because Index 0 is
already taken by the control you placed on the form at design time.
Each control that you add in this way initially has the same
properties as the original control. You’ll have to change at least the Top and
Left properties to prevent all the added controls from displaying at the same
The variable rs
refers to a recordset that contains
information about rooms in a dormitory. The code goes through the recordset and for each room, creates a Label control (lblRoom), and then a ListBox control (lstRoom). It then positions them in a grid on the form.
ROOM_LIST_HEIGHT and ROOM_LIST_WIDTH are constants that specify the control
size and are defined elsewhere.
col = 0
row = 0
Do While Not rs.EOF
recordnumber = rs.AbsolutePosition
lblRoom(recordnumber).Caption = “Room ” & rs.Fields(“RoomNumber”).Value
lblRoom(recordnumber).Top = row * (ROOM_LIST_HEIGHT * 1.3) + 300
lblRoom(recordnumber).Left = col * (ROOM_LIST_WIDTH * 1.2) + 500
lblRoom(recordnumber).Visible = True
lstRoom(recordnumber).Left = lblRoom(recordnumber).Left
lstRoom(recordnumber).Top = lblRoom(recordnumber).Top + _
lblRoom(recordnumber).Height + 10
lstRoom(recordnumber).Visible = True
col = col + 1
If col = 3 Then
col = 0
row = row + 1
Adding controls to a form at runtime can give your program
the flexibility that’s necessary to react to changing data and circumstances.
Peter Aitken has been programming with Visual Basic since Version
1.0. He has written numerous books and magazine articles on Visual Basic and
other computer and programming topics.