Adding and Deleting Controls at Run Time Example

To try this example, paste the code into the Declarations section of a form containing one option button, two command buttons, and a large picture box.  Set the Index property for the option button to 0 to create a control array.  Set the Caption property to "Add" for one command button and "Delete" for the other.  Then press F5.  Each time an option button is clicked, the BackColor property of the picture box is reset.  Clicking a command button causes an option button to be added or deleted depending on which one is chosen.

Dim MaxId                                ' Declare variable.
Sub Option1_Click (Index As Integer)
  Picture1.BackColor = QBColor(Index + 1)
End Sub

Sub Command1_Click ()
  If MaxId >= 9 Then Exit Sub            ' No more than 10 buttons.
  MaxId = MaxId + 1                      ' Increment button count.
  Load Option1(MaxId)                    ' Create new button.
  Option1(0).SetFocus                    ' Reset button selection.
  ' Set new button under previous button.
  Option1(MaxId).Top = Option1(MaxId - 1).Top + 360
  Option1(MaxId).Visible = True          ' Display new button.
End Sub

Sub Command2_Click ()
  If MaxId = 0 Then Exit Sub             ' Keep first button.
  Unload Option1(MaxId)                  ' Delete last button.
  MaxId = MaxId - 1                      ' Decrement button count.
  Option1(0).SetFocus                    ' Reset button selection.
End Sub