Often the user will need to select from or add to a list of items such as pay code abbreviations or division names. Visual Basic supports two controls, the List Box and the Combo Box controls, that you use to display lists and from which the user can select items in the lists.
Once you master the List controls, two additional VB programming topics are simple: data arrays and control arrays. You can combine the List controls and the arrays to work in harmony when processing lists of information, as you'll see in this lesson.
The highlights of this hour include
Figure 10.1 shows VB's Options dialog box that appears when you select Tools |
Options and click the Editor Format tab. The dialog box illustrates a List Box control.
You've seen list boxes throughout your work with Windows; list boxes appear on many
forms and dialog boxes. The List Box control gives the user a choice of several values.
The user selects an option instead of typing a value into a text box. The list box
ensures that the user always chooses one of the available options.
Figure 10.1. The List Box control gives the user a choice of options.
NOTE: The list box displays scrollbars if the list box is not tall enough or wide enough to display all its data.
As you place the list box on the form, think about the data the list box will hold and try to size the list box so that it's large enough to hold the data. Of course, you don't always know a list box's data in advance because the data might come from a disk file or from the user at the keyboard, but try to make the control large enough to hold the data you expect. Your form's size and surrounding controls might limit the size of your list box, so the scrollbars often appear.
Any list box can have a single or multiple columns. In many situations the single column makes data selection easier for your users, but they will have to scroll through more values to locate the item they want to find. Figure 10.2 shows a form with two list boxes; the first list box is a single-column list box, and the second displays three columns. (The Columns property determines the list box's number of columns.)
To familiarize yourself with list boxes as quickly as possible, look over the
property values in Table 10.1. You'll work with other properties at runtime because
you often initialize the list box at runtime and not at design time.
Figure 10.2. A list box with one column and one with three columns.
Table 10.1. The basic list box properties.
|BackColor||Specifies the list box's background color.|
|Columns||Determines the number of columns. If 0, the list box scrolls vertically in a single column. If 1 or more, the list box items appear in the number of columns specified (one or more columns) and a horizontal scrollbar appears so you can see all the items in the list.|
|ForeColor||Specifies the list box's text color.|
|Height||Indicates the height of the list box in twips.|
|IntegralHeight||Determines whether the list box can display partial items, such as the upper half of an item that falls toward the bottom of the list box.|
|List||Holds, in a drop-down property list box, values that you can enter into the list box at design time. You can enter only one at a time, and most programmers usually prefer to initialize the list box at runtime.|
|MultiSelect||The state of the list box's selection rules. If 0-None (the default), the user can select only one item by clicking with the mouse or by pressing the Spacebar over an item. If 1-Simple, the user can select more than one item by clicking with the mouse or by pressing the Spacebar over items in the list. If 2-Extended, the user can select multiple items using Shift+click and Shift+arrow to extend the selection from a previously selected item to the current one. Ctrl+click either selects or deselects an item from the list.|
|Sorted||Determines whether the list box values are automatically sorted. If False (the default value), the values appear in the same order in which the program added the items to the list.|
|Style||Determines whether the list box appears in its usual list format or, as shown in Figure 10.3, with check boxes next to the selected items.|
Figure 10.3. You can add check boxes to list box items.
TIP: You can add a command button that operates in conjunction with the list box in many situations. The user can, therefore, select a value from the list box and then click the command button to inform your application of the selected value. You can also add a double-click event procedure to the list box so that the user's double-click on a list box item selects that item. If you set up the command button first, the double-click event procedure is simple because you can trigger the command button's Click() event procedure from within the double-click procedure with this one line:cmdAccept_Click ` Triggers the button's click event
Table 10.2 describes the methods available to the list box. Remember that methods are routines a control knows how to execute. List boxes use methods more than any other control you've learned about so far. The methods help the user initialize, add items to, and remove items from list boxes.
Table 10.2. Common list box methods.
|AddItem||Adds a single item to the list box.|
|Clear||Removes all items from the list box.|
|List||A string array that holds items from within the list box.|
|ListCount||The total number of list box items.|
|RemoveItem||Removes a single item from the list box.|
Perhaps the most important method is the AddItem method, which adds items to the list box. AddItem is to list boxes what the assignment statement is to variables. A method always appears between the control name and a period. For example, the following AddItem method sends the value of Joseph to a list box named lstOneCol:
NOTE: The one-column list box shown in Figure 10.1 is named lstOneCol and that's the name used throughout the next couple examples.
You'll often initialize a list box in the Form_Load() event procedure that initializes the form and the form controls right before the form appears on the screen. The following code sends several people's names to the list boxes shown earlier:
lstOneCol.AddItem "Joseph" lstOneCol.AddItem "Michael" lstOneCol.AddItem "Stephanie" lstOneCol.AddItem "Mary Ann" lstOneCol.AddItem "Pamela" lstOneCol.AddItem "Jock" lstOneCol.AddItem "Bobby" lstOneCol.AddItem "Cliff" lstOneCol.AddItem "Jerry" lstOneCol.AddItem "Thomas" lstOneCol.AddItem "George" lstOneCol.AddItem "Robert"
You'll initialize both single-column and multicolumn list boxes the same way with
AddItem. The number of columns the list box contains has no bearing on how
you initialize the list box.
Each item in a list box contains an associated subscript. The subscript is a number that begins at 0 for the first item, the second subscript is 1, and so on. Therefore, if you apply the RemoveItem method as follows, the third item is removed (because of the first item's 0 subscript):
lstOneCol.RemoveItem(2) ` 3rd item has a subscript of 2
New Term: A subscript is a value that distinguishes one array item from the other array items.
As you remove list box items, the remaining item subscripts adjust upward accordingly. Therefore, if a list box contains seven items, each item has a subscript that ranges from 0 to 6. If you remove the fourth item, the list box items will then range from 0 to 5; the subscript 5 will now indicate the same item that the subscript 6 indicated before RemoveItem removed the fourth item.
You can remove all items from the list box with Clear, like this:
lstOneCol.Clear ` Remove all items
You can assign individual items from a list box that contains data using the List method. You must save list box values in String or Variant variables unless you convert the items to a numeric data type using Val() first. The following statements store the first and fourth list box items in two String variables:
strVar1 = lstOneCol.List(0) strVar2 = lstOneCol.List(3)
The List method requires a subscript so Visual Basic knows which value from the list to assign to the variable. The value remains in the list after the assignment, but now the value appears in the variable as well.
You use ListCount to determine the number of items in the list box currently defined. The following statement stores the number of list box items in a numeric variable named intNum:
intNum = lstOneCol.ListCount
TIP: You use ListCount to loop through an entire list box with a For-Next loop.
You use Selected to determine whether a user has selected a list box
item. Selected returns True for one or more list box items if the
items' MultiSelect property is set to either 1-Simple or 2-Extended.
Those properties indicate that the user can select more than one item at once. Figure
10.4 shows a list box with several items selected at the same time.
Figure 10.4. A list box with a MultiSelect property set to 1 or 2.
Combo boxes work much like list boxes except that the user can add items to a combo box at runtime, whereas the user can only scroll and select items from a list box at runtime. Visual Basic supports three kinds of combo boxes, and the kind you select depends on the combo box you want to display on the form and on the ability you want the user to have. All the list box methods that you learned about in the previous section apply to combo boxes.
Here are the three kinds of combo boxes:
TIP: Think of a combo box as being a combination List Box and Text Box control. The user sees items in the list but then enters additional items in the text box portion of the combo box.
Figure 10.5 shows the three kinds of combo boxes. Each combo box contains the
names of people that you saw in Figure 10.4. The first combo box, the drop-down combo
box, is normally closed; when the user clicks the combo box's down arrow, the combo
box opens. The third combo box, the drop-down list box, is left unopened. If the
user opens the drop-down list box, the user will see a list of people's names but
will not be able to add to the names because no data entry is possible in drop-down
Figure 10.5. Use Style to change the combo box appearance.
TIP: Study your form's design and determine the best list control to use. If the user must enter values, you should use either a drop-down combo or simple combo box. If the user only selects a value from a list, use a list box if you have enough form space or use a drop-down list box if you don't have a lot of room to display a full-sized list box.
Table 10.3 describes some of the combo box properties.
Table 10.3. The fundamental combo box properties.
|BackColor||The combo box's background color.|
|ForeColor||The combo box's foreground text color.|
|Height||The height, in twips, of the closed combo box.|
|IntegralHeight||Determines whether the combo box can display partial items, such as the upper half of an item that falls toward the bottom of the combo box.|
|List||A drop-down property list box in which you can enter values into the combo box at design time. You can enter only one at a time, and most programmers prefer to initialize the combo box at runtime.|
|Sorted||Determines whether the combo box values are automatically sorted. If False (the default value), the values appear in the same order in which the program added the items to the combo box.|
|Style||Determines the type of combo box your application needs. If 0-DropDown Combo, the combo box is a drop-down combo box. If 1-Simple Combo, the combo box turns into a simple combo box that remains open to the height you use at design time. If 2-DropDown List, the combo box turns into a drop-down list box that remains closed until the user is ready to see more of the list.|
WARNING: The user's entered value does not add to the Drop-down Combo Box control or to the Simple Combo Box control unless you add the capability to capture the user's entry. The combo box by itself, without code, cannot handle the addition of items automatically. You need to write, in the combo's Change or LostFocus event procedure, enough code to add the new item (that always appears in the combo's Text property) to the combo box list, like this:cboBox.AddItem cboBox.Text ` Adds user's value to the box
You can also add a command button that adds the user's entered combo box value if the user clicks the command button and ignores the new value in Text.
TIP: Run Visual Basic's sample application named ListCombo (in the VB\Samples\Pguide folder) to see the difference between a normal list box and a combo box list box.
Now that you've mastered list boxes and combo boxes, you will have little trouble understanding data arrays. An array is nothing more than a list of variables. Regular non-array variables, as opposed to arrays, have separate names such as the following:
curSales97 sngTaxRate intCount blnIsRecorded
Variables in an array all have the same name. Therefore, an array that holds a list of 10 division sales figures might be named curDivSales. Your program must be capable of distinguishing between an array's variables, and with the single name this distinction might seem impossible. Nevertheless, as with list boxes, your program can distinguish between array variables by using a subscript. The subscript works just like an index value. The first value in the array would be subscripted as curDivSales(0) (subscripts start at 0 unless you use the Option Base 1 statement in a general module to start the array's subscripts at 1). The second value in the array would be curDivSales(1), and so on.
An array is a list of items with the same name and type.
NOTE: Even without Option Base 1, programmers often ignore the zero subscript and don't reference it. Your programming preferences determine the starting subscript that you want to use.
Figure 10.6 illustrates how an array such as the 10-element curDivSales
resides in memory.
Figure 10.6. Distinguishing array elements with subscripts.
To declare an array, you use Dim or Public just as you declare regular non-array variables. In the declaration, specify the number of elements the array is to hold. The following Dim statement declares the 10-element Currency array named curDivSales:
Dim curDivSales(10) As Currency
NOTE: All elements in an array must be the same data type.
Here's the great benefit that arrays give you over separate variable names: When you need to work with a group of variables, if you don't use an array, you must list each variable. Therefore, if you want to add all the divisions' sales figures and they are stored in separate non-array variables, you would have to code something like this:
curTotal = curDivSales0 + curDivSales1 + curDivSales2 + _ curDivSales3 + curDivSales4 + curDivSales5 + _ curDivSales6 + curDivSales6 + curDivSales7 + _ curDivSales8 + curDivSales9
TIP: If you want to break a long Code window statement into two or more lines, terminate each continued line with the underscore character, as shown in the CurTotal assignment.
An array makes stepping through and totaling the data much simpler. Here is the code that uses a For-Next loop to add the items in an array:
curTotal = 0 ` Zero out the total ` Step through the elements For intCtr = 0 To 9 intTotal = intTotal + curDivSales(intCtr) ` Add elements Next intCtr ` curTotal not holds the sum of all 10 values
With only 10 variables, does the array make for a lot less coding than separate variables? With only 10 variables, the array does not seem to offer a lot of space advantages or coding shortcuts. What, however, if there were 1,000 variables that you needed to track and total? By making a simple change to the For-Next loop, you can easily add together all 1,000 elements, like this:
curTotal = 0 ` Zero out the total ` Step through the elements For intCtr = 0 To 999 intTotal = intTotal + curDivSales(intCtr) ` Add elements Next intCtr ` curTotal not holds the sum of all 1,000 values
Again, many programmers ignore the 0 subscript and start the subscript at 1, so this loop would become the following:
curTotal = 0 ` Zero out the total ` Step through the elements For intCtr = 1 To 1000 intTotal = intTotal + curDivSales(intCtr) ` Add elements Next intCtr ` curTotal not holds the sum of all 1,000 values
Suppose you need to ask the user for several values, such as the names of children in a class. By declaring a string array, a For-Next loop makes getting the names simple, as you can see here:
For intCtr = 1 To 10 strChildName(intCtr) = InputBox("What is the next child's name?") Next intCtr
WARNING: Remember that if you use a starting subscript of 1, you must declare one more element than you actually need due to the 0-based subscript that you're ignoring. Therefore, the previous code's strChildName's array declaration would be Dim strChildName(11) As String.
A control array is a list of controls with the same name. Therefore, instead of using four command buttons with four separate names, you can place a command button control array on the form, and that control array holds four command buttons. The control array can have a single name, and you'll distinguish the controls from each other with a subscript.
TIP: Use a control array if several controls on your form are to look and act similar to each other, such as multiple command buttons or two or more list boxes.
One of the best reasons to use a control array is that you can add the first control to your form and set all its properties. When you create a control array from that first control, all the elements in the control array take on the same property values. You then can change those properties that need to be changed without having to set every property for every control individually.
New Term: A control array is an array of several controls that you reference with an Index property value that acts as the subscript. The controls in a control array must be the same control type.
Control arrays have a lot in common with data arrays. A control array has one name, and you distinguish all the array's controls from each other with the zero-based subscript. (The Index property holds the control's subscript number.) All the control array elements must be the same data type.
As soon as you place a control on a form that has the same name as an existing control, Visual Basic makes sure that you want to begin a control array by issuing the warning message shown in Figure 10.7. The message box keeps you from accidentally creating a control array when you actually want to add a different control. You'll see Figure 10.7's message box when you copy an existing control to the Clipboard and paste the copy elsewhere onto the form. If you click the message box's No button, Visual Basic uses a default control name for the placed control.
Fig 10.7 Visual Basic asks whether you want a control array.
All event procedures that use controls from a control array require a special argument value passed to them that determines which control is being worked on. For example, if your application contains a single command button named cmdTotal, the Click() event procedure begins and ends as follows:
Private Sub cmdTotal_click () End Sub
If, however, you created a control array named cmdTotal, the Click() event procedure begins and ends like this:
Private Sub cmdTotal_click (Index As Integer) End Sub
The procedure uses the Index argument as the control index number (the subscript) that the user clicked. Therefore, if you want to change the clicked command button's Caption property inside the cmdTotal_Click() procedure, you would do so like this:
cmdTotal(Index).Caption = "A new Caption value"
The Index value holds the command button's index the user clicked to generate the event procedure so you will always respond to the proper control clicked if you use Index after the control array name.
In this hour you have learned how you can add lists of items to your application. The first kind of list, the List Box control, lets your users select from a list of items that your application displays. The combo box works like a list box but lets the user enter new values into the list.
Data and control arrays help you streamline your programs. Instead of working with separate variable or control names, you can work with a single name and use a subscript value to distinguish between the items. The code to process 10 or 100 array items is virtually the same, as this lesson demonstrated.
Hour 11, "Additional Controls," teaches several new controls that you can add to your applications.
The quiz questions and exercises are provided for your further understanding. See Appendix C, "Answers," for answers.