Visual Basic in 12 Easy Lessons vel11.htm

Previous Page TOC Next Page



Lesson 6, Unit 11


Arrays and Lists



What You'll Learn


Variables and controls hold the data that your Visual Basic programs process. You've now seen the different kinds of variable data types that Visual Basic supports, as well as three of the primary controls used on forms: command buttons, labels, and text boxes.

This unit extends the discussion on variables and controls by showing you a new way of managing variable data storage. By storing variables in arrays, you'll be able to process larger amounts of data with less code than you could with the kinds of variables that you've seen so far.

After you learn about the concept of arrays and how you access variable arrays, you'll discover three more controls that you can place on forms. These controls, the list box and combo box controls, give you a simple way to display array data on forms.

Arrays Hold Data


Concept: An array is a table of values in memory. Unlike variables to which you assign different names, multiple variables stored in arrays all have the same name. You'll reference the different data values using a subscript.

All the variables that you've worked with so far require a unique variable name. As you define variables, you define both the variable data types and the variable names. Figure 11.1 shows what you have defined once Visual Basic executes the following variable definitions and assignments:


Dim Age As Integer

Dim Limit As Long

Dim Salary As Single

Dim DogName As String

' Store data in the variables

Age = 34

Limit = 40294

Salary = 982343.23 ' A Visual Basic programmer's pay

DogName = "Ralph"

Figure 11.1. Variables appear in several different memory locations.

Although Visual Basic might define and assign the variables back to back in memory, you don't know or even care where Visual Basic stores the variables. With such variable definitions, all you need are four variables of four data types, and each of those variables has a different name.

For variables that fulfill a different purpose, such variable definitions are excellent and work well for simple as well as advanced Visual Basic applications. Nevertheless, there will be times when you'll need several variables of the same data type to hold similar data values. For example, a tag agent's application might need to tally a grand total of all license fees for that day's transactions. If there are one hundred transactions, the only way that you know to define one hundred variables is to define and name each of them differently with statements such as these:



Dim LicFee1, LicFee2, LicFee3, LicFee4 As Currency

Dim LicFee5, LicFee6, LicFee7, LicFee8 As Currency

Dim LicFee9, LicFee10, LicFee11, LicFee12 As Currency

' The rest of the variable definitions would follow

When you need to define variables that hold the same kind of data values, such as this table of 100 tag agent license values, your program gets burdened down with all those variable names. Filling those variables is a problem as well. Will you supply one hundred text box controls on a form? If the clerk at the counter enters each customer's license amount as the customer pays, how can you collect the next license fee in the next variable?

Even if you could find a way to fill the one hundred variables with the daily values, how would you get a total of that data? You would have to write multiple addition statements that begin something like this:


DayTotal = LicFee1 + LicFee2 + LicFee3 + LicFee4

DayTotal = 
DayTotal + LicFee5 + LicFee6 + LicFee7

DayTotal = DayTotal + LicFee8 + LicFee9 + LicFee10

' Ugh! This could take forever!

Again, the variables that you've worked with so far have been great for applications that don't need to process several sets of related data. Computers are used for processing sets of data, however. You may recall from the previous lesson that the power of a computer comes mostly from its capability to loop through code at a high rate of speed, processing large amounts of data quickly and without getting bored. Those large amounts of data must be stored in something other than the stand-alone variables that you've seen so far or the programmer would soon get bogged down with writing huge numbers of variable names every time another calculation was needed.



Definition: An array is a list of values.

Visual Basic supports the use of arrays to eliminate much of the tedium that you would face if every variable had to have a different name. Rather than define single stand-alone variables using several Dim statements, you can define an entire list of variables. This list, called an array, takes on the following attributes:



Note: There are two additional ways to declare arrays, using Dim and the Global statement, that you'll learn about in Lesson 8.

Figure 11.1's variables could not be stored in an array because their data types are different. The tag agent's one hundred license fees, however, would make excellent array candidates because each fee requires the same data type (Currency).

You'll use the Static statement for this lesson to define arrays. Static works a lot like Dim except that Static defines arrays rather than single stand-alone variables. Here is the format of Dim:


Static ArName(subMax) As DataType

The ArName is the name that you want to call the array. subMax must be a number that describes the total number of array elements you need. The DataType is a data type that matches one of Visual Basic's data types, such as Single and Long.



Warning: As with any kind of variable, you'll have to define arrays with Static before you can use them.

Stop and Type: Here is the simple way that the tag agent might define the 100 license fee variables:


Dim LicFee(100) As Currency ' Defines 100 elements

Review: By defining an array of data, you can define multiple occurrences of variable data without having to assign each variable a different name and without having to define each variable separately. The array will have a single name and be stored together, with all of the array values being sequentially back to back, in memory. You'll access each value using a unique subscript.

Output: Figure 11.2 shows how the LicFee appears in memory.

Figure 11.2. Array elements appear back to back and each has a unique subscript that begins at 0.

Analysis: Visual Basic automatically defines an extra array element with the subscript of 0 when you define an array. The Option Base 1 statement that you can put in the (general) procedure of any form's Code window tells Visual Basic to define arrays with a starting subscript of 1. Without Option Base 1, however, when you request 100 elements, Visual Basic throws in the extra zero subscript. Most Visual Basic programmers choose to ignore the zero subscript, however, and if you do, too, you won't be wasting too much memory by ignoring the extra array element. This book will always ignore the zero-based subscript and work with a starting subscript of 1. If you want to ignore the zero subscript, you can do that without coding the Option Base 1 statement.

Visual Basic assigns each element in the array a subscript so that your program can distinguish between each value in the array. As with all variables, Visual Basic assigns zero to each array element, and your program will overwrite those initial zeros when the program assigns data to the array.



Warning: Don't ever attempt to reference a subscript that doesn't exist for a particular array. Visual Basic would issue an error message if your program attempted to do something with LicFee(311) or LicFee(-8) because 311 and -8 are out of the range of LicFee's subscripts that range only from 0 to 100.


The Advantage of Arrays


Concept: Arrays eliminate much tedious coding. By using the subscript rather than a different variable name, you can use a For loop to step through arrays and access individual items in sequence.

Arrays simplify the process of initializing, printing, calculating, and storing data. If, for example, you were to define an array of 20 string variables that will hold customer names like this:


Dim CustNames(20) As 
String

you could initialize each of those 20 strings with 20 InputBox$() function assignments, like this:


CustName(1) = InputBox$("What is the next customer's name?")

CustName(2) = 
InputBox$("What is the next customer's name?")

CustName(3) = InputBox$("What is the next customer's name?")

CustName(4) = InputBox$("What is the next customer's name?")

CustName(5) = InputBox$("What is the next 
customer's name?")

CustName(6) = InputBox$("What is the next customer's name?")

CustName(7) = InputBox$("What is the next customer's name?")

CustName(8) = InputBox$("What is the next customer's name?")

CustName(9) = 
InputBox$("What is the next customer's name?")

' And so on for all 20 names

Wouldn't the following For loop be easier, though?


For Ctr = 1 To 20

 CustName(Ctr) = InputBox$("What is the 
next customer's name?")

Next Ctr

The variable, Ctr, steps through the values from 1 to 20, assigning the result of the InputBox$() function for each of those 20 times. The following similar code could display the 20 names in message boxes:


For Ctr = 1 To 20

 MsgBox CustName(Ctr)

Next Ctr

Of course, the constant display of input and message boxes can get tedious, but focus for now on the programming ease that arrays provide over variables that each have different names. Using a For loop for stepping through an array of values makes working with that array a breeze.



Note: Of course, you don't have to step through every array value when you need to work with only a few of them. For example, you could display only the 5th and 19th customer with two back-to-back message boxes like this:
MsgBox CustName(5)
MsgBox CustName(19)
An array gives you another way to reference data than by using a different variable name. Each element, however, is a unique variable known by its array name and subscript. Therefore, you can work with individual array elements as if they were stand-alone variables by accessing their individual subscripts.


Stop and Type: Listing 11.1 contains a calculating section of code from a procedure that finds the average of the license fee transactions. The array named LicFee had already been filled with values earlier in the procedure. Those values may have come from the form, from the user with input boxes, or from a disk file.

Review: The array subscripts enable you to access one or more elements from the array. The big advantage that arrays provide is enabling your program to step through the entire array using a For loop's control variable as the subscript.

Listing 11.1. Computing an average license fee from an array.


1: TotalFee = 0.0 ' TotalFee is defined as Currency

2: AvgFee = 0.0 ' AvgFee is defined as a Currency

3: For Ctr = 1 To 
100 ' There are 100 license fees

4: TotalFee = TotalFee + LicFee(Ctr)

5: Next Ctr

6: ' Now that the total is computed, calculate average

7: AvgFee = TotalFee / 100.0

Analysis: Before studying Listing 11.1, think about how you compute the average of numbers. You first add all the numbers together, then divide by the total number to get an average. That process is exactly what this code does. The For loop in lines 3 through 5 moves the values from 1 to 100 into the variable named Ctr during each loop iteration. Line 4 adds each of the array values, one at a time as controlled by the For loop, to the TotalFee variable.

After all one hundred license fees are added together, line 7 then computes the average of the one hundred values. Subsequent code could either display the average in a label or use the value for another calculation.

List Boxes: Controls That Work Like Arrays


Concept: The list box control works a lot like an active array on your form that the user can scroll through, seeing all the items in the list. Often, programmers initialize list boxes with data from arrays. Unlike most controls, you can't add values to a list box control through the Property window, but must add the values at runtime through code.

Figure 11.3 shows the location of the list box control on the Toolbox window. The list box control displays values through which the user can scroll. The list box doesn't display scroll bars if the size of the list box is large enough to display all the values. Remember that list boxes are for displaying data; the user cannot add data directly to a list box.

Figure 11.3. The location of the list box control.



Tip: To remind yourself how the list box control works, you may want to load and run the CONTROLS.MAK project once again and scroll through the values in the list box control in the application.

Table 11.1 contains the list of property values that you can set for list box controls. You've seen many of the properties before because several controls share many of the same properties.

Table 11.1. The list box properties.

Property Description
BackColor The background color of the list box. It's a hexadecimal number representing one of thousands of possible Windows color values. You can select from a palette of colors displayed by Visual Basic when you're ready to set the BackColor property. The default background color is the same as the form's default background color.
Columns If 0 (the default), 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) which the user scrolls the list box horizontally to see all the items if needed. Figure 11.4 shows two identical list boxes, one with a Columns property of 0 and one with a Columns property of 3.
DragIcon The icon that appears when the user drags the list box control around on the form. (You'll only rarely allow the user to move a list box control, so the Drag... property settings aren't usually relevant.)
DragMode Either contains 1 for manual mouse dragging requirements (the user can press and hold the mouse button while dragging the control) or 0 (the default) for automatic mouse dragging, meaning that the user can't drag the list box control but that you, through code, can initiate the dragging if needed.
Enabled If set to True (the default), the list box control can respond to events. Otherwise, Visual Basic halts event processing for that particular control.
FontBold True (the default) if the list values are to display in boldfaced characters; False otherwise.
FontItalic True (the default) if the list values are to display in italicized characters; False otherwise.
FontName The name of the list box's text style. Typically, you'll use the name of a Windows TrueType font.
FontSize The size, in points, of the font used for the list box values.
FontStrikethru True (the default) if the list values are to display in strikethru letters (characters with a dash through each one); False otherwise.
FontUnderline True (the default) if the list box values are to display in underlined letters; False otherwise.
ForeColor The color of the values inside the list box.
Height The height, in twips, of the list box control.
HelpContextID If you add advanced, context-sensitive help to your application), the HelpContextID provides the identifying number for the help text.
Index If the list box control is part of a control array, the Index property provides the numeric subscript for each particular list box control (see the next unit).
Left The number of twips from the left edge of the Form window to the left edge of the list box control.
MousePointer The shape that the mouse cursor changes to if the user moves the mouse cursor over the list box control. The possible values are from 0 to 12 and represent a range of different shapes that the mouse cursor can take. (See Lesson 12.)
MultiSelect If 0-None (the default), the user can select only one list box 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 item. Ctrl+click either selects or deselects an item from the list.
Name The name of the control. By default, Visual Basic generates the names List1, List2, and so on as you add subsequent list box controls to the form.
Sorted If True, Visual Basic doesn't display the list box values sorted numerically or alphabetically. If False (the default), the values appear in the same order in which the program added them to the list.
TabIndex The focus tab order begins at 0 and increments every time that you add a new control. You can change the focus order by changing the controls' TabIndex to other values. No two controls on the same form can have the same TabIndex value.
TabStop If True, the user can press Tab to move the focus to this list box. If False, the list box can't receive the focus.
Tag Unused by Visual Basic. This is for the programmer's use for an identifying comment applied to the list box control.
Top The number of twips from the top edge of a list box control to the top of the form.
Visible True or False, indicating whether or not the user can see (and, therefore, use) the list box control.
Width The number of twips wide that the list box control consumes.

Figure 11.4. Two identical list boxes with different Columns property settings.

When placing a list box control on the form, decide how tall you want the list box to be by resizing the control to the size that fits the form best. Remember that if all the list box values don't all fit within the list box, Visual Basic adds scroll bars to the list box so that the user can scroll through the values.

Table 11.2 contains all the list box events that you can program. Table 11.2 contains all the list box events that you can use in a program. You'll rarely write event procedures for list box controls, however. Most of the time, you'll let the user scroll through the list box values to see information they need; programs don't need to respond to list box events as often as they need to respond to command buttons and text boxes.

Table 11.2. The list box control's events.

Event Description
Click Occurs when the user clicks the list box control
DblClick Occurs when the user double-clicks the list box control
DragDrop Occurs when a dragging operation of the list box completes
DragOver Occurs during a drag operation
GotFocus Occurs when the list box receives the focus
KeyDown Occurs when the user presses a key as long as the KeyPreview property is set to True for the controls on the form; otherwise, the form gets the KeyDown event
KeyPress Occurs when the user presses a key over the list box
KeyUp Occurs when the user releases a key over the list box
LostFocus Occurs when the list box loses the focus to another object
MouseDown Occurs when the user presses a mouse button over the list box
MouseMove Occurs when the user moves the mouse over the list box
MouseUp Occurs when the user releases a mouse button over the list box

Table 11.3 contains a list of list box control methods that you'll need to use for initializing, analyzing, and removing items from a list box control. Methods works like miniature programs that operate on controls. Here is the format of a method's use on a list box named lstItems:


lstItems.AddItem "Arizona"

The control name always precedes the method and the dot operator. Any data needed by the method appears to the right of the method.

Table 11.3. List box methods.

Method Name Description
AddItem Adds a single item to the list box
Clear Clears all items from the list
List A string array that holds each item within the list box
ListCount The total number of items in a list box
RemoveItem Removes a single item from a list box
Selected Determines whether the user has selected a particular item in the list box

Use the AddItem method to add properties to a list box control. Suppose that you want to add a few state names to a list box named lstStates. The following code adds the state names:


' 
Add several states to a list box control

lstStates.AddItem "Arizona"

lstStates.AddItem "Alabama"

lstStates.AddItem "Oklahoma"

lstStates.AddItem "New York"

lstStates.AddItem "California"


lstStates.AddItem "Nebraska"

lstStates.AddItem "Ohio"

lstStates.AddItem "Florida"

lstStates.AddItem "Texas"

lstStates.AddItem "South Dakota"

lstStates.AddItem "Nevada"

lstStates.AddItem 
"Illinois"

lstStates.AddItem "New Mexico"

This code would most likely appear in the Form_Load() event procedure so that the list boxes are initialized with their values before the form appears and before the list boxes are seen on the form.



Note: The list box acts a little like an array.

Each item in a list box has a subscript just as each element in an array has a subscript. The first item that you add to a list box has a subscript of 0, the second has a subscript of 1, and so on. To remove the third item from the list box, therefore, your code can apply the RemoveItem method, as follows:


lstStates.RemoveItem(2) ' 3rd item has a subscript of 2


Caution: Keep in mind that, as you remove items from a list box, the remaining item subscripts adjust 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 of 5 will indicate the same item that the subscript of 6 indicated before the RemoveItem method removed the fourth item.

If you want to remove all items from the list box, use the Clear method. The following simple method removes all the state names from the state list box:


lstStates.Clear ' Remove all items

You can assign individual items from a list box control that contains data by using the List method. You must save list box values in string or variant variables unless you convert list box items to a numeric data type using Val() first. The following assignment statements store the first and fourth list box item in two string variables:


FirstStringVar = lstStates.List(0)

SecondStringVar = lstStates.List(3)

The ListCount method always provides the total number of items in the list box control. For example, the following statement stores the number of list box items in a numeric variable named Num:


Num = lstStates.ListCount

The Selected method returns either a true or false value that determines whether a user has selected a list box item. The Selected method returns true for possibly more than one list box item if the 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 11.5 shows a list box with several items selected at the same time.

Figure 11.5. A list box with a MultiSelect property set to 1 or 2.

Stop and Type: The code in Listing 11.2 stores every selected item of a list box named lstStates in a string array. The string array is defined with enough elements to hold all the items if the user happens to have selected all fifty items that were first added to the list box.

Review: A list box control holds one or more values through which the user can scroll. Unlike many other controls, the user can only look at and select items in the list box, but not add items to the list box. Through methods, you can, however, add items, delete items, and check for selected items in the list box by using the methods inside your code procedures.

Listing 11.2. Storing all selected values in a string array.


1: Dim SelectStates(50) As String

2: Dim StSub As Integer ' State array subscript

3: StSub = 1

4: For Ctr = 0 To 49 ' 50 states in all

5: If (lstStates.Selected(Ctr) = 
True) Then

6: SelectStates(StSub) = lstStates.List(Ctr)

7: StSub = StSub + 1

8: End If

10: Next Ctr

Analysis: Line 2 must define a subscript that will keep track of the state's string array. Line 3 initializes the starting subscript to 1 because the zero subscript is ignored throughout this book's programs; this is the standard followed by most Visual Basic programmers.

Lines 4 through 10 contain a loop that steps through all fifty states that were stored in the list box earlier (perhaps in the Form_Load() event procedure). If a state has been selected by the user (line 5 checks for the selection), the Selected method returns a true result and line 6 stores the selected list box item in the string array. Line 7 increments the string array's subscript to prepare the state array subscript for further possible assignments in subsequent iterations through the loop.

Combo Boxes


Concept: Combo boxes work a little like list boxes except that the user can add items to a combo box at runtime. There are three kinds of combo boxes determined by the Style property. The AddItem and RemoveItem methods are popular for combo boxes, although all of the list box methods that you learned in the previous lesson apply to combo boxes as well.

Figure 11.6 shows the location of the combo box control on the Toolbox window. No matter what kind of combo box you want to place on the form, you'll use the same combo box control on the toolbox to add the combo box to the form.

Figure 11.6. The location of the combo box control.

There are three kinds of combo boxes, as follows:

Figure 11.7 shows the three kinds of combo boxes. Each combo box contains the names of states that you saw earlier in list boxes. The first combo box, the dropdown combo box, is normally closed; when the user clicks the combo box's down arrow, the combo box opens. The third combo box, the dropdown list box, is left unopened. If the user opens the dropdown list box, the user will see a list of state names but will not be able to add to the state names because no data entry is possible in dropdown list boxes.

Figure 11.7. The three combo box styles.

Table 11.4 contains a description of every combo list property value that you can set in the Property window.

Table 11.4. The combo box properties.

Property Description
BackColor The background color of the combo box. This is a hexadecimal number representing one of thousands of possible Windows color values. You can select from a palette of colors displayed by Visual Basic when you're ready to set the BackColor property. The default background color is the same as the form's default background color.
DragIcon The icon that appears when the user drags the combo box control around on the form. (You will only rarely allow the user to move a combo box control, so the Drag... property settings aren't usually relevant.)
DragMode Either contains 1 for manual mouse dragging requirements (the user can press and hold the mouse button while dragging the control) or 0 (the default) for automatic mouse dragging, meaning that the user can't drag the combo box control but that you, through code, can initiate the dragging if needed.
Enabled If set to True (the default), the combo box control can respond to events. Otherwise, Visual Basic halts event processing for that particular control.
FontBold True (the default) if the combo values are to display in boldfaced characters; False otherwise.
FontItalic True (the default) if the combo values are to display in italicized characters; False otherwise.
FontName The name of the combo box's text style. Typically, you'll use the name of a Windows TrueType font.
FontSize The size, in points, of the font used for the combo box values.
FontStrikethru True (the default) if the combo values are to display in strikethru letters (characters with a dash through each one); False otherwise.
FontUnderline True (the default) if the combo box values are to display in underlined letters; False otherwise.
ForeColor The color of the values inside the combo box.
Height The height, in twips, of the combo box control.
HelpContextID If you add advanced, context-sensitive help to your application), the HelpContextID provides the identifying number for the help text.
Index If the combo box control is part of a control array, the Index property provides the numeric subscript for each particular combo box control. (See the next unit).
Left The number of twips from the left edge of the Form window to the left edge of the combo box control.
MousePointer The shape that the mouse cursor changes to if the user moves the mouse cursor over the combo box control. The possible values are from 0 to 12 and represent a range of different shapes that the mouse cursor can take. (See Lesson 12.)
Name The name of the control. By default, Visual Basic generates the names Combo1, Combo2, and so on as you add subsequent combo box controls to the form.
Sorted If True, Visual Basic doesn't display the combo box values sorted numerically or alphabetical. If False (the default), the values appear in the same order in which the program added them to the list.
Style The default, 0-Dropdown Combo, produces a dropdown combo box control. 1-Simple Combo turns the combo box into a simple combo box control. 2-Dropdown list turns the combo box into a dropdown list box control.
TabIndex The focus tab order begins at 0 and increments every time that you add a new control. You can change the focus order by changing the controls' TabIndex to other values. No two controls on the same form can have the same TabIndex value.
TabStop If True, the user can press Tab to move the focus to this combo box. If False, the combo box can't receive the focus.
Tag Unused by Visual Basic. This is for the programmer's use for an identifying comment applied to the combo box control.
Text The initial value only that the user sees in the combo box.
Top The number of twips from the top edge of a combo box control to the top of the form.
Visible True (the default) or False, indicating whether the user can see (and, therefore, use) the combo box control.
Width The number of twips wide that the combo box control consumes.


Note: Notice that there is no MultiSelect combo box property as there is with list box controls. The user can select only one combo box item at any one time.

Table 11.5 contains a list of the combo box events for which you can write matching event procedures when your program must react to a user's manipulation of a combo box.

Table 11.5. The combo box control's events.

Event Description
Change Occurs when the user changes the value in the data entry portion of the dropdown combo or the simple combo box; not available for dropdown list boxes because the user can't change data in them
Click Occurs when the user clicks the combo box control
DblClick Occurs when the user double-clicks the combo box control
DragDrop Occurs when a dragging operation of the combo box completes
DragOver Occurs during a drag operation
DropDown Occurs when the user opens a dropdown combo box or a dropdown list box
GotFocus Occurs when the combo box receives the focus
KeyDown Occurs when the user presses a key as long as the KeyPreview property is set to True for the controls on the form; otherwise, the form gets the KeyDown event
KeyPress Occurs when the user presses a key over the combo box
KeyUp Occurs when the user releases a key over the combo box
LostFocus Occurs when the combo box loses the focus to another object

The combo box controls support the same methods that the list box controls support. Therefore, you can add, remove, count, and select items from the combo box if you apply the methods seen in Table 11.3.

Stop and Type: Listing 11.3 contains a command button's event procedure that adds a value to a combo box's list of items. Unlike text box controls, you'll need to provide the user with some data entry mechanism, such as a command button, that informs the program when to use the AddItem method to add an item to a combo box.



Note: Listing 11.3 assumes that another procedure, such as the Form_Load() procedure, added the initial values to the combo box.

Review: The three kinds of combo boxes offer three similar controls with which your program can interact by showing lists of values and, optionally, allowing the user to enter values in the lists. Two of the combo boxes are dropdown lists that don't consume form space until the user opens the combo boxes.

Listing 11.3. A command button's event procedure that adds an item to a combo box.


1: Sub cmdSimple_Click ()

2: ' Add the user's item to the simple combo

3: comSCtrl.AddItem comSCtrl.Text

4: comSCtrl.Text = ""

5: comSCtrl.SetFocus

6: End Sub

Output: Figure 11.8 contains a screen that you saw in the second lesson of the book. The CONTROLS.MAK application demonstrates the simple combo box and shows how you can set up an application to add items to a list of values.

Figure 11.8. Adding data to a simple combo box control.

Analysis: The command button in Figure 11.8 is named cmdSimple, so clicking the command button executes the event procedure shown in Listing 11.3. Line 3 stores the combo box's Text property value to that combo box's list of items. The combo box will not contain a user's entry in the upper data entry portion of the combo box until an AddItem method adds that entry to the list. The Text property always holds the current value shown in the data entry portion of the combo box, but the AddItem method must add that value to the list.

As soon as the user's entry is added, line 4 erases the data entry portion of the combo box. After all, the user's text will now appear in the lower listing portion of the combo box (thanks to line 3), so line 4 clears the data entry area for more input. In addition, line 5 sets the focus back to the combo box (the focus appears in the data entry area that line 4 cleared) so that the user is ready to add an additional item to the combo box.

Homework



General Knowledge


  1. How can arrays help you process large amounts of data?

  2. What is an array element?

  3. What is an array subscript?

  4. If an array contains 20 elements, how many names does the array have?

  5. If an array contains 20 elements, how many subscripts does the array have (assume that there is an Option Base 1 statement in the (general) procedure section of the Code window).

  6. True or false: Every element in an array must be the same data type.

  7. How can you differentiate between array elements?

  8. What statement defines arrays inside event procedures?

  9. Assuming that there is an Option Base 1 statement in the (general) procedure section of the Code window, what is the starting subscript for all arrays that you subsequently define in the program?

  10. Which loop works best for array processing?

  11. Which controls work like arrays?

  12. True or false: The user can enter new values in list boxes.

  13. True or false: The user can select more than one value in a list box.

  14. True or false: A list box may consist of more than one column.

  15. Why are methods important for list box and combo box controls?

  16. Which event procedure do programmers often use to initialize list and combo box controls?

  17. True or false: There are three kinds of combo boxes.

  18. True or false: There are three kinds of combo box controls on the toolbox.

  19. True or false: The list box methods work well for the combo boxes also.

  20. True or false: List and combo box controls have subscripts just as arrays have.

  21. What is the method that indicates whether a list box item is selected?

  22. True or false: A simple combo box can be opened with a user's click of the simple combo box's down arrow.


Write Code That...


  1. Paul wants to ensure that all items in his list box are sorted. Which property should Paul set to 1-Sorted?

  2. Suppose that you want to define an array of three high school student ages in a list. Write the Static statement that defines the ages.

  3. What list box property would you set to 1 or 2 if you wanted to allow the user to select from multiple list box items at one time?

  4. Mary wants to erase all list box items when the user clicks a special command button named cmdGoAway. Write the event procedure needed to erase the list box named lstVals if the user clicks the cmdGoAway command button.

  5. Why should you offer a command button for the user to use when adding items to a combo box control?

Find the Bug

  1. Carla needs to define a list box with 24 items in it. In the Form_Load() event procedure, Carla attempts this:
    Static lstData(24) ' Define 24 list boxes
    Tell Carla what she's doing incorrectly.


Extra Credit


Write an application that asks the user, with an InputBox() function, whether he or she wants to see a dropdown combo box, a simple combo box, or a dropdown list box. Ask the user, in the InputBox() prompt string, to type a 1, 2, or 3 to indicate which of the three kinds of combo boxes are requested. Use a loop to check that the user enters a proper value, and if the user enters a value other than 1, 2, or 3, keep prompting until the user enters one of the three values. Then display a list of ten ice cream flavors in that particular combo box control. Hint: Assign the user's entry to the combo box's Style property.

Previous Page Page Top TOC Next Page