Controls Scenario: Adding and Deleting Controls in a Control Array

The control array example demonstrates how controls — in this case, option buttons — are added and deleted at run time. The example allows the user to add option buttons that change the background color of a picture box.

Start with a form, and then draw a picture box, a label, two option buttons, and three command buttons, as shown in Figure 7.3.

Figure 7.3   Adding controls at run time

The following table lists the property settings for the objects in the application.

Object Property Setting
Form Caption Control Array Example
Picture box Name picDisplay
Label Caption Select an option button to display a new color
Option1 Name
Index
optButton
0
Option2 Name
Index
optButton
1
First command button Name
Caption
cmdAdd
&Add
Second command button Name
Caption
cmdDelete
&Delete
Third command button Name
Caption
cmdClose
&Close

Events in the Control Array Application

Next, you need to add the event procedures for the option buttons and command buttons. Start by adding the form declaration:

Dim MaxId As Integer

The Click event procedure is shared by all the option buttons:

Private Sub optButton_Click (Index As Integer)
   picDisplay.BackColor = QBColor(Index + 1)
End Sub

New option buttons are added by the Click event procedure for the Add command button. In this example, the code checks that no more than ten option buttons are loaded before the Load statement is executed. Once a control is loaded, its Visible property must be set to True.

Private Sub cmdAdd_Click ()
   If MaxId = 0 Then MaxId = 1   ' Set total option
                                 ' buttons.
   If MaxId > 8 Then Exit Sub   ' Only ten buttons
                                 ' allowed.
   MaxId = MaxId + 1         ' Increment button count.
   Load optButton(MaxId)      ' Create new button.
   optButton(0).SetFocus      ' Reset button selection.
   ' Set new button under previous button.
   optButton(MaxId).Top = optButton(MaxId - 1)._
   Top + 400
   optButton(MaxId).Visible = True   ' Display new
                                 ' button.
   optButton(MaxId).Caption = "Option" & MaxId + 1
End Sub

Option buttons are removed by the Click event procedure for the Delete command button:

Private Sub cmdDelete_Click ()
   If MaxId <= 1 Then Exit Sub   ' Keep first two
                                 ' buttons.
   Unload optButton(MaxId)      ' Delete last button.
   MaxId = MaxId - 1            ' Decrement button count.
   optButton(0).SetFocus      ' Reset button selection.
End Sub

The Close button Click event ends the application:

Private Sub cmdClose_Click ()

   Unload Me
End Sub