Freetutes.com

VB6 beginners tutorial - Learn VB6

Advanced VB6 tutorial - Learn Advanced VB6

VB .NET - Learn Visual Basic .NET

Systems Analysis - System analysis and Design tutorial for Software Engineering

Browse Topics

- Getting started
- Data Types
- Modules
- Operators in VB6
- VB6 Variable
- VB6 Procedures
- VB6 Control Structures
- Loops in VB6
- VB6 Exit Do & With End With
- Arrays in VB6
- User-Defined Data Types
- VB6 Constants
-
VB6 Built-in Functions
- Date and Time in VB6
- VB6 Controls
- TextBox Control
- ComboBox & OptionButton
- Label & Frame
- PictureBox & ImageBox
- Timer Control
- ListBox & ComboBox
- VB6 ScrollBar
- Control Arrays in VB6
- Files controls in VB6
- VB6 CheckBox
- Forms in VB6
- Menus in VB6
- MDI Form in VB6
- InputBox
- MessageBox
- Mouse events
- Mouse Move
- Error Handling
-
Error Handling (2)
-
VB6 Database


You are here: Visual Basic > VB6 (Beginners Tutorial)

Previous Page | Table of Contents | Next Page

Control Arrays in Visual Basic 6

A control array is a group of controls that share the same name type and the same event procedures. Adding controls with control arrays uses fewer resources than adding multiple control of same type at design time.

A control array can be created only at design time, and at the very minimum at least one control must belong to it. You create a control array following one of these three methods:

  • You create a control and then assign a numeric, non-negative value to its Index property; you have thus created a control array with just one element.

  • You create two controls of the same class and assign them an identical Name property. Visual Basic shows a dialog box warning you that there's already a control with that name and asks whether you want to create a control array. Click on the Yes button.

  • You select a control on the form, press Ctrl+C to copy it to the clipboard, and then press Ctrl+V to paste a new instance of the control, which has the same Name property as the original one. Visual Basic shows the warning mentioned in the previous bullet.

Control arrays are one of the most interesting features of the Visual Basic environment, and they add a lot of flexibility to your programs:

  • Controls that belong to the same control array share the same set of event procedures; this often dramatically reduces the amount of code you have to write to respond to a user's actions.

  • You can dynamically add new elements to a control array at run time; in other words, you can effectively create new controls that didn't exist at design time.

  • Elements of control arrays consume fewer resources than regular controls and tend to produce smaller executables. Besides, Visual Basic forms can host up to 256 different control names, but a control array counts as one against this number. In other words, control arrays let you effectively overcome this limit.

The importance of using control arrays as a means of dynamically creating new controls at run time is somewhat reduced in Visual Basic 6, which has introduced a new and more powerful capability.

Don't let the term array lead you to think control array is related to VBA arrays; they're completely different objects. Control arrays can only be one-dimensional. They don't need to be dimensioned: Each control you add automatically extends the array. The Index property identifies the position of each control in the control array it belongs to, but it's possible for a control array to have holes in the index sequence. The lowest possible value for the Index property is 0. You reference a control belonging to a control array as you would reference a standard array item:

Text1(0).Text = ""

Sharing Event Procedures

Event procedures related to items in a control array are easily recognizable because they have an extra Index parameter, which precedes all other parameters. This extra parameter receives the index of the element that's raising the event, as you can see in this example:

Private Sub Text1_KeyPress(Index As Integer, KeyAscii As Integer)
MsgBox "A key has been pressed on Text1(" & Index & ") control"
End Sub

The fact that multiple controls can share the same set of event procedures is often in itself a good reason to create a control array. For example, say that you want to change the background color of each of your TextBox controls to yellow when it receives the input focus and restore its background color to white when the user clicks on another field:

Private Sub Text1_GotFocus(Index As Integer)
Text1(Index).BackColor = vbYellow
End Sub
Private Sub Text1_LostFocus(Index As Integer)
Text1(Index).BackColor = vbWhite
End Sub

Control arrays are especially useful with groups of OptionButton controls because you can remember which element in the group has been activated by adding one line of code to their shared Click event. This saves code when the program needs to determine which button is the active one:

' A module-level variable
Dim optFrequencyIndex As Integer

Private Sub optFrequency_Click(Index As Integer)
' Remember the last button selected.
optFrequencyIndex = Index
End Sub

Creating Controls at Run Time

Control arrays can be created at run time using the statements

  • Load object (Index %)

  • Unload object (Index %)

Where object is the name of the control to add or delete from the control array. Index % is the value of the index in the array. The control array to be added must be an element of the existing array created at design time with an index value of 0. When a new element of a control array is loaded, most of the property settings are copied from the lowest existing element in the array.

Following example illustrates the use of the control array.

* Open a Standard EXE project and save the Form as Calculator.frm and save the Project as Calculater.vbp.

* Design the form as shown below.

Object
Property
Setting
Form

Caption

Name

Calculator

frmCalculator

CommandButton

Caption

Name

Index

1

cmd

0

CommandButton

Caption

Name

Index

2

cmd

1

CommandButton

Caption

Name

Index

3

cmd

2

CommandButton

Caption

Name

Index

4

cmd

3

CommandButton

Caption

Name

Index

5

cmd

4

CommandButton

Caption

Name

Index

6

cmd

5

CommandButton

Caption

Name

Index

7

cmd

6

CommandButton

Caption

Name

Index

8

cmd

7

CommandButton

Caption

Name

Index

9

cmd

8

CommandButton

Caption

Name

Index

0

cmd

10

CommandButton

Caption

Name

Index

.

cmd

11

CommandButton

Caption

Name

AC

cmdAC

CommandButton

Caption

Name

+

cmdPlus

CommandButton

Caption

Name

-

cmdMinus

CommandButton

Caption

Name

*

cmdMultiply

CommandButton

Caption

Name

/

cmdDivide

CommandButton

Caption

Name

+/-

cmdNeg

TextBox

Name

Text

txtDisplay

( empty )

CommandButton

Caption

Name

=

cmdEqual

The following variables are declared inside the general declaration

Dim Current As Double
Dim Previous As Double
Dim Choice As String
Dim Result As Double

The following code is entered in the cmd_Click( ) (Control Array) event procedure

Private Sub cmd_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & cmd(Index).Caption
'&is the concatenation operator
Current = Val(txtDisplay.Text)
End Sub

The following code is entered in the cmdAC_Click ( ) event procedure

Private Sub cmdAC_Click()
Current = Previous = 0
txtDisplay.Text = ""
End Sub

The below code is entered in the cmdNeg_Click( ) procedure

Private Sub cmdNeg_Click()
Current = -Current
txtDisplay.Text = Current
End Sub

The following code is entered in the click events of the cmdPlus, cmdMinus, cmdMultiply, cmdDevide controls respectively.

Private Sub cmdDevide_Click()
txtDisplay.Text = ""
Previous = Current
Current = 0
Choice = "/"
End Sub

Private Sub cmdMinus_Click()
txtDisplay.Text = ""
Previous = Current
Current = 0
Choice = "-"
End Sub

Private Sub cmdMultiply_Click()
txtDisplay.Text = ""
Previous = Current
Current = 0
Choice = "*"
End Sub

Private Sub cmdPlus_Click()
txtDisplay.Text = ""
Previous = Current
Current = 0
Choice = "+"
End Sub

To print the result on the text box, the following code is entered in the cmdEqual_Click ( ) event procedure.

Private Sub cmdEqual_Click()

Select Case Choice

Case "+"
Result = Previous + Current
txtDisplay.Text = Result
Case "-"
Result = Previous - Current
txtDisplay.Text = Result
Case "*"
Result = Previous * Current
txtDisplay.Text = Result
Case "/"
Result = Previous / Current
txtDisplay.Text = Result
End Select

Current = Result

End Sub

Save and run the project. On clicking digits of user's choice and an operator button, the output appears.

Iterating on the Items of a Control Array

Control arrays often let you save many lines of code because you can execute the same statement, or group of statements, for every control in the array without having to duplicate the code for each distinct control. For example, you can clear the contents of all the items in an array of TextBox controls as follows:

For i = txtFields.LBound To txtFields.UBound
txtFields(i).Text = ""
Next

Here you're using the LBound and UBound methods exposed by the control array object, which is an intermediate object used by Visual Basic to gather all the controls in the array. In general, you shouldn't use this approach to iterate over all the items in the array because if the array has holes in the Index sequence an error will be raised. A better way to loop over all the items of a control array is using the For Each statement:

Dim txt As TextBox
For Each txt In txtFields
txt.Text = ""
Next

A third method exposed by the control array object, Count, returns the number of elements it contains. It can be useful on several occasions (for example, when removing all the controls that were added dynamically at run time):

' This code assumes that txtField(0) is the only control that was
' created at design time (you can't unload it at run time).
Do While txtFields.Count > 1
Unload txtFields(txtFields.UBound)
Loop

Arrays of Menu Items

Control arrays are especially useful with menus because arrays offer a solution to the proliferation of menu Click events and, above all, permit you to create new menus at run time. An array of menu controls is conceptually similar to a regular control array, only you set the Index property to a numeric (non-negative) value in the Menu Editor instead of in the Properties window.

There are some limitations, though: All the items in an array of menu controls must be adjacent and must belong to the same menu level, and their Index properties must be in ascending order (even though holes in the sequence are allowed). This set of requirements severely hinders your ability to create new menu items at run time. In fact, you can create new menu items in well-defined positions of your menu hierarchy—namely, where you put a menu item with a nonzero Index value—but you can't create new submenus or new top-level menus.

Now that you have a thorough understanding of how Visual Basic's forms and controls work, you're ready to dive into the subtleties of the Visual Basic for Applications (VBA) language.

( Download the source code )

Previous Page | Table of Contents | Next Page


  

   

Home | About Us | Privacy Policy | Contact Us

Copyright © Freetutes.com | All Rights Reserved