Control Arrays

Definition:

A control array is a grouping of controls that provide similar functionality. 

-------------------

Characteristics:

-------------------

Justification:

Control arrays use fewer resources than the equivalent controls maintained separately, because control array elements share code.

-------------------

Bounds:

-------------------

Creation:

Control arrays can be created several ways:

The first three techniques are self explanatory and the last one will be discussed in depth in a later section.

When either of the first two techniques are used the user will be prompted as to whether or not a control array is to be created with the dialog below:

  

 

-------------------

Count property:

The number of elements in a control array can be determined using the Count property.   

ex: lblLabels.Count

-------------------

UBound and LBound:

UBound and LBound are control properties that return a control array's upper and lower bounds, respectively.  

ex:  lblLabels.Lbound 

-------------------

Method Item:

Any individual control in a control array can be accessed using method Item. For example, the statement 

lblLabels.Item(33).Caption = "Control Index is 33!" 

sets the Caption property for the control array element with an Index of 33. 

-------------------

Accessing:

In order to access a control that is part of a control array, specify the Index property in parentheses after the control name. 

ex: txtName(12).Text = "Fred"

The value of Index identifies which button (control element) was accessed, so it is often available in control array event procedures.   

ex: Private Sub txtName_Click (Index As Integer)
             txtName(Index).Text = "I'm index number" & index
      End Sub

The normal event procedure for a text box wouldn't have the Index parameter, but the event procedure for a control array of text boxes does.  The Index parameter returns the Index property value of the control that triggered the event.

-------------------

Creating New Instances of Control Arrays at Runtime:

In order to create a control array at runtime, at least one element has to have been placed on the form at design time, and its Index property set to 0.

To create further instances of the control at runtime, use the Load statement.

Assuming that txtName(0) already exists on the form, the following code will create 5 additional elements in the control array:

For I = 1 to 5
    Load txtName(I)
    txtName(I).Visible = True
Next I

When each new control is created, most of its properties are set to the same values as the control on which it was based.  The Visible property is an exception, and must be set to True in order to display the control.

The new controls will still not be visible until they are assigned a new location on the form, otherwise they all occupy the same position on the form.  The Top, Left, Height, and Width properties -- which are used to specify the object's position on the form -- are set to the same value as the control on which the new controls are based.  An example of repositioning new controls is shown below, but in most cases either the Left property, the Top property, or both must be modified.

-------------------

Code for printing a square on a control array of buttons:  

*Note that a control array is created at runtime if the size of the array is not known beforehand.

Private Sub drawSquare(ByVal numElts as Integer)
    Dim ctr as Integer, row as Integer, col as Integer
    Dim left as Long, top as Long, width as Long, height as Long

    left = cmdSquare(0).left                                                        ' store originals
    top = cmdSquare(0).top
    height = cmdSquare(0).height
    width = cmdSquare(0).width
    cmdSquare(0).Visible = False                                            ' hide original

    ctr = 1
    For row = 1 to numElts
          For col = 1 to numElts
               Load cmdSquare(ctr)                                                    ' create element
               cmdSquare(ctr).Visible = True                                    ' display element
               cmdSquare(ctr).BackColor = (&HFFFFC0)              ' set color
               cmdSquare(ctr).left = left + (col * width)                    ' create grid
               cmdSquare(ctr).top = top + (row * height)
               cmdSquare(ctr).picture = LoadPicture("numeral.gif")  ' add picture 
               ctr = ctr + 1
          next col
      next row
end Sub

 

Recap:  To create a control array element at runtime

-------------------

Note that in the preceding program a two-dimensional array was displayed using a one-dimensional control array.  While the nested loops ranged through the values for row and col, the variable ctr was used to track the index of the control array element.  Instead of using ctr, the index could have been calculated using the formula: 

(row - 1) * numElts + col 

Array index* Control array index
1,1 1
1,5 5
2,1 6
3,3 13

* for numElts = 5 and option base 1

======================

Note:  The following refers to controls and NOT control arrays!

Creating Controls at Runtime:

It is possible to create controls dynamically at runtime by using control arrays.  Controls can be created at runtime by using the Add method of the Controls collection. 

The following program segment shows the code that must be used to create a commandButton purely from code, without having to drag a CommandButton from the ToolBox first.   

'WithEvents is a way to tell the program to
'respect all the events that are associated with
'a CommandButton such as the Click event.

    Private WithEvents cmdSquare As CommandButton

    Private Sub Form_Load()
           Set cmdSquare = Controls.Add("VB.CommandButton", "cmdSquare")
            With cmdSquare
                 .Visible = True
                 .Caption = "Square"
                 .Left = 1000
             End With

     End Sub

     Sub cmdSquare_Click( )
            cmdSquare.Caption = "Clicked!"
     End Sub

-------------------

Note:  I haven't figured out how to use a control created at runtime as the basis for a control array so that we can create new elements of the control array at runtime.  If you wish to experiment and figure it out, please share it with me.

-------------------

Syntax

object.Add (ProgID, name, container)

The Add method syntax has these parts:

Part Description
object Required. An object expression that evaluates to an object in the Applies To list.
ProgID Required. A string that identifies the control. The ProgID of most controls can be determined by viewing the Object Browser. The ProgID is composed of the Library and Class of the control. For example, the CommandButton control's ProgID is VB.CommandButton. In cases where the ProgID differs from that shown in the Object Browser, Visual Basic displays an error message that contains the correct ProgId.
name Required.  A string that identifies the member of the collection.
container Optional. An object reference that specifies a container of the control. If not specified or NULL, defaults to the container to which the Control's collection belongs. You can put a control in any existing container control (such as the Frame control) by specifying this argument. A user control or an ActiveX document can also be a container.