A collection of similar variables, in which each has the same name and all are of the same type, is an array. Remember that a variable can be thought of as a cup that holds an unknown value or an always changing value (see Figure 11.1).
FIGURE 11.1 A variable is a placeholder for a specific type of value.
Think of an array, then, as a collection of cups. Each cup in the collection can hold the same type of data, and every cup in the collection has the same name. Each cup within the collection is an element and has a number assigned to it that reflects its position within the collection. The first element of an array usually has a position number of 0 (zero).
Arrays can be different sizes (see Figure 11.2). One array might have three elements, another might have 30 elements, and it's even possible for an array to have no elements at all--only the possibility of having elements that are created at a later time.
FIGURE 11.2 An array is a collection of variables.
You can declare, or dimension, an array in two ways: as you would a single variable and by using the To keyword.
To declare an array as you would a single variable, you use the following syntax:
Dim|Public|Private ArrayName(Subscript) As DataType
In this syntax,
Option baseWhen you declare an array, the first element of the array is usually 0 (zero). It's possible, however, to force the first element of an array to be 1. To do this, insert the statement Option Base 1 in the General section of a module within your project. You have to do this only when you want the first element of your array to be element number 1.
Therefore, to declare an array of integers with five elements in it, you would use the following:
Dim iMyArray(4) As Integer
To assign a value to each element in the array iMyArray, you would use the following:
iMyArray(0) = 9 iMyArray(1) = 342 iMyArray(2) = 2746 iMyArray(3) = 0 iMyArray(4) = 8901
To change the value of the fourth element of the array iMyArray from 0 (zero) to 45, you would do as follows:
iMyArray(3) = 45
To declare an array of nine strings global to your entire program, you would use the code in Listing 11.1.
01 Public strMyArray(8) As String
02
03 strMyArray(0) = "I am a pitcher."
04 strMyArray(1) = "I am a catcher."
05 strMyArray(2) = "I play first base."
06 strMyArray(3) = "I play second base."
07 strMyArray(4) = "I play third base."
08 strMyArray(5) = "I play shortstop."
09 strMyArray(6) = "I play left field." 10 strMyArray(7) = "I play center field."
11 strMyArray(8) = "I play right field."
You can also declare an array by using the To keyword within the subscript syntax. For example, if you want to create an array of five Integer variables in which the first element is number 1 and the last element is number 5, you use
Dim iMyArray(1 To 5) as Integer
This method provides an easy way to start your element numbering at a value other than 0 (zero).
Although you usually set the number of elements in an array when you declare it, it's possible to alter the size of the array. When you change the number of elements in an existing array, you redimension it. To do so, use the ReDim keyword in the following syntax:
ReDim [Preserve] ArrayName(Subscript) As DataType
In this syntax,
Using ReDim in your codeThe actual implementation of the ReDim statement is different from this conceptual illustration. If you create an array that you'll later redimension, you can't hard code the element size of the array when you first declare it. Therefore, in practice, the code here won't redimension the array declared in Listing 11.1.
The following code shows how, conceptually, to redimension the array strMyArray (from Listing 11.1) to contain 10 elements:
ReDim Preserve strMyArray(9) strMyArray(9) = "I am the designated hitter."
To create an array that you'll later resize, you must first create the array without any elements. Listing 11.2 shows the proper way to create an array that you'll later redimension.
01 `Create an array without any elements
02 Dim strMyArray() as String
03
04 `Dimension the array for 9 elements
05 ReDim strMyArray(8)
06
07 `Assign values to the array elements
08 strMyArray(0) = "I am a pitcher."
09 strMyArray(1) = "I am a catcher."
10 strMyArray(2) = "I play first base."
11 strMyArray(3) = "I play second base."
12 strMyArray(4) = "I play third base."
13 strMyArray(5) = "I play shortstop."
14 strMyArray(6) = "I play left field."
15 strMyArray(7) = "I play center field."
16 strMyArray(8) = "I play right field."
17
18 `Add an element and make it so all the values
19 `of the previous elements are kept intact
20 ReDim Preserve strMyArray(9)
21
22 `Assign a value to the new array element
23 strMyArray(9) = "I am the designated hitter."
Notice in Listing 11.2 that the first ReDim statement (line 5) doesn't use the Preserve keyword. You can do this because initially there are no values within the array to preserve. In the second ReDim statement on line 20, however, the Preserve keyword is very important because the pre-existing elements have assigned values that you don't want to lose. If you didn't use the Preserve keyword in the second ReDim statement, strMyArray would have the following values:
strMyArray (0) = "" strMyArray (1) = "" strMyArray (2) = "" strMyArray (3) = "" strMyArray (4) = "" strMyArray (5) = "" strMyArray (6) = "" strMyArray (7) = "" strMyArray (8) = "" strMyArray (9) = "I am the designated hitter."
Remember, arrays are tricky. Be careful!
So far, the arrays in this chapter have been one-dimensional arrays--that is, they are a one-row collection of variables, as seen in Figure 11.2. In Visual Basic, however, you can create arrays that have up to 60 dimensions. Usually, two-dimensional arrays will suffice for most introductory programming projects, and most likely you won't need to make an array of more than three dimensions.
Think of a two-dimensional array as a tic-tac-toe board--a set of columns and rows that intersect to form a grid. Each grid cell has a location defined as ColumnNumber, RowNumber. Figure 11.3 is a conceptual illustration of iVar(2,4), a two-dimensional array of integers. Notice that each element is defined by the coordinates of the column position and the row position. For example, the array element iVar(0, 0) is 5 and the element iVar(2,2) is 49.
To create a two-dimensional array, use the following syntax:
Dim|Public|Private ArrayName(SubscriptOfCols, _ SubscriptOfRows) As DataType
In this syntax,
FIGURE 11.3 Think of a two-dimensional array as a collection of cups arranged in columns and rows.
Therefore, to declare the array shown in Figure 11.3, you would use the following syntax:
Dim iVar(2,4) as Integer
Whereas you can consider a two-dimensional array to be a rectangle, you can consider a three-dimensional array to be a rectangular block. To declare a three-dimensional array of integers, use
Dim iVar(1,2,1) as Integer
Figure 11.4 is a conceptual illustration of the three-dimensional array defined in the preceding line.
FIGURE 11.4 A three-dimensional array (1,2,1) has 12 elements. It's two columns wide by three rows tall by two planes deep.
In the array iVar, the value assigned to each element, as depicted in Figure 11.4, is as follows:
iVar(0,0,0) = 5 iVar(0,1,0) = 187 iVar(0,2,0) = 16 iVar(1,0,0) = 12 iVar(1,1,0) = 55 iVar(1,2,0) = 7 iVar(0,0,1) = 34 iVar(0,1,1) = 13 iVar(0,2,1) = 4500 iVar(1,0,1) = 612 iVar(1,1,1) = 9 iVar(1,2,1) = 784
Just as with a one-dimensional array, you can use the To keyword when declaring the subscript range of each dimension in a multidimensional array. Thus, the line
Dim dMyArray(1 To 5, 3 To 8, 3 To 5) As Double
would declare a three-dimensional array of Double values, five columns wide by six rows tall by three planes deep.
You can also use the Redim keyword to resize a multidimensional array. If you use the Preserve keyword, however, only the last dimension of a multidimensional array can be resized, and the number of dimensions can't be changed.
You can use the For...Next loop that you learned about in Chapter 10, "Working with Loops," to move through, or traverse, an array. This can be useful when you want to change or report values in an array.
Listing 11.3 is an example of using a For...Next loop to traverse an array. The listing is the event procedure for a button click, in which an array of 20 elements is created. A For...Next loop is used twice--first to assign values to every element in the array, and then to find the value assigned to every element and make a string that reports the value of that element (see Figure 11.5).
01 Private Sub cmdTraverse_Click()
02 Dim i%
03 Dim iMyArray%(19) As Integer
04 Dim BeginMsg$
05 Dim MidMsg$
06 Dim LoopMsg$
07 Dim FullMsg$
08
09 `Assign a value to each element in the array
10 `by using a loop to traverse to each element
11 `in the array.
12 For i% = 0 To 19
13 `Make the value of the element to be
14 `twice the value of i%
15 iMyArray%(i%) = i% * 2
16 Next i%
17
18 `Create the BeginMsg$ string
19 BeginMsg$ = "The element is: "
20 MidMsg$ = ", The value is: "
21 `Go through the array again and make
22 `a string to display
23 For i% = 0 To 19
24 LoopMsg$ = LoopMsg$ & BeginMsg$ & CStr(i%)
25 LoopMsg$ = LoopMsg$ & MidMsg$ & iMyArray(i%)
26
27 `Concatenate the loop message to the
28 `full message. Also add a line break
29 FullMsg$ = FullMsg$ & LoopMsg$ & vbCrLf
30
31 `Clean out the loop message so that
32 `new value next time through the loop
33 LoopMsg$ = ""
34 Next i%
35
36 txtTraverse.Text = FullMsg$
37 End Sub
FIGURE 11.5 This program sets the value of each array element to twice its element number.
The code in Listing 11.3 is simple. Remember that a For...Next loop increments a counting variable as it loops. You assign this counting variable to the element position of the array. Then, set the lower bound of the array (the lowest element number) to the start point of the loop and set the upper bound of the array (the highest element number) to the end point of the loop. When you run the loop, the counting variable will always be at an element of the array.
Of all the standard controls, the ListBox and ComboBox are best suited for categorizing and listing information from which users can make choices and selections. These controls are closely related, and the manner in which you manipulate them is almost identical. The difference is that the ComboBox combines a ListBox control with a TextBox (hence the name) and allows users to select from a list or type a new value.
Both the ListBox and ComboBox controls can handle lists. In Visual Basic, a list is an array of strings formally referred to with the List property. (The List property is common to the ListBox and ComboBox controls.) Most work that you do with ListBoxes and ComboBoxes involves adding and removing strings from the List property. You can add strings to the List property of a ListBox or ComboBox at design time or runtime.
Add strings to a ListBox or ComboBox at design time
At design time, the strings you added to the List property will appear in the ListBox on the form (see Figure 11.8).
FIGURE 11.6 You can add strings to a ListBox or a ComboBox at design time by entering values in the List property drop-down list.
FIGURE 11.7 To add multiple items to a ListBox list at design time, press Ctrl+Enter.
FIGURE 11.8 You can view a ListBox's list at design time.
This design-time method for populating the List property is useful when your program starts up. Because the contents of a ListBox or ComboBox can change frequently while your program is running, however, you need to be able to add and remove items to and from the List property while it's running. To do this, the ListBox and CombBox controls make extensive use of the AddItem, RemoveItem, and Clear methods.
To add a string to the List of a Listbox or ComboBox during runtime, use the AddItem method, which has the following syntax:
Object.AddItem StringToAdd
In this syntax,
Listing 11.4 shows you how to use the AddItem method in a form's Load event procedure to add strings to the List of a ListBox. Figure 11.9 shows the result of the form's Load event.
01 Private Sub Form_Load()
02 lstHero.AddItem "Superman"
03 lstHero.AddItem "Batman"
04 lstHero.AddItem "Green Lantern"
05 lstHero.AddItem "Aquaman"
06 lstHero.AddItem "SpiderMan"
07 lstHero.AddItem "Daredevil"
08 lstHero.AddItem "Hulk"
09 End Sub
FIGURE 11.9 You can use the AddItem method in a formís Load event to initialize the List property of a ListBox control.
To understand how Visual Basic determines the value of a string selected in the List of a ListBox or ComboBox, you need to understand that a List is an array of strings. As you learned earlier in this chapter, an array is declared as follows:
Dim ArrayName(Subscript) As DataType
Therefore, if you declared a four-element array as MyArray(3), you would list the elements in that array as follows:
MyArray(0) MyArray(1) MyArray(2) MyArray(3)
If you want to determine the value assigned to the second element, you could use the following statement (remember, by default the first element is MyArray(0)):
MyValue = MyArray(1)
The ListBox and ComboBox controls use a similar format. The property List is the general term that Visual Basic uses to refer to the entire array of strings within a ListBox or ComboBox. Therefore, to find the value of the second string in the ListBox called lstHero (from Listing 11.4), you would use the following statement:
SecondString$ = lstHero.List(1)
The value of SecondString$ is "Batman".
For a ListBox or ComboBox, the selected item in a list is contained in the ListIndex property. When you select a string in a ListBox, Visual Basic assigns the position number of that string to the ListIndex property of the control. Therefore, to determine the value of the selected string in lstHero (from Listing 11.4), you would use the following code:
Private Sub lstHero_Click() lblHero.Caption = lstHero.List(lstHero.ListIndex) End Sub
This is the event procedure for the Click event of the lstHero ListBox control. When the user clicks a string in the ListBox, the code executes and reports back the value of the selection within the Caption property of the Label named lblHero. Figure 11.10 shows what happens when the user selects a string.
FIGURE 11.10 You can program the Click, MouseUp, or MouseDown events of a ListBox to find the value of a user's selection.
A faster way to find out the value of the string a user selects in a ListBox or ComboBox is to use the Text property. For example, you can use the following for a ListBox:
Dim strMyStr as String strMyStr = List1.Text
For a ComboBox, use the following:
Dim strMyStr as String strMyStr = Combo1.Text
You remove a string from a list in a ListBox or ComboBox by using the RemoveItem method:
Object.RemoveItem Index
In this syntax
Figure 11.11 shows an enhancement to the program presented in Figure 11.10. A button has been added to remove the string that the user selects from the ListBox. Listing 11.5 shows the RemoveItem method used in code.
01 Private Sub cmdRemove_Click()
02 lstHero.RemoveItem (lstHero.ListIndex)
03 lblHero.Caption = ""
04 End Sub
When you remove an item from a ListBox or ComboBox, make sure that you clear the text from the Caption property of the Label control lblHero, as shown in line 3 of Listing 11.5. If you don't do this, the user will remove the string from the ListBox, but it will remain in the Label control.
FIGURE 11.11 A CommandButton provides a way for the user to remove an item from a list.
If you want to remove all the strings contained in a ListBox or ComboBox, use the Clear method:
Object.Clear
In this syntax
Thus, one line of code can be used to clear all the strings in the ListBox of the program shown in Figure 11.11:
lstHero.Clear
The ListBox and ComboBox controls have much in common, but each has a distinct use. A ListBox takes up more room than a ComboBox, and when using a ListBox, you can't select or input unlisted data. A ComboBox offers more flexibility and uses a form's space more efficiently.
A ComboBox's Style property enables you to change the operational characteristics and appearance of the control. Table 11.1 describes these styles, and Figure 11.12 shows the ComboBox styles applied to a form. You can also download this code from http://www.mcp.com/info. You will be asked for an ISBN. Enter 078971633x and click the Search button to go to the Using Visual Basic 6 page.
Using a simple combo ComboBoxWhen you first add a ComboBox with the 1 - Simple Combo style to a form, the ComboBox is sized so that none of the ListBox is displayed. Increase the Height property to display more of the ListBox.
Setting | Description |
0 - Drop-down Combo | A drop-down list. However, users can also enter new data to the ComboBox by inputting text directly into the TextBox portion of the ComboBox. |
1 - Simple Combo | A combination of a TextBox and a ListBox that doesn't drop down. Users can select data from the ListBox or type new data into the TextBox. The size of a simple ComboBox includes both edit and list portions. |
2 - Drop-down List | A read-only drop-down list from which users can only select data. Users can't enter data into the control. |
FIGURE 11.12 Notice that with a drop-down ComboBox style, you can add new data to the control at runtime.
The most common ComboBox styles are 0 - Drop-down Combo and 2 - Drop-down List. As mentioned earlier, you use a drop-down ComboBox style when you want to let users add new data that's not in the ComboBox's list. You use the drop-down list style when you want users to choose from data that's only in the drop-down list of the ComboBox.
The Baseball ScoreKeeper program uses many things you've just learned. It uses arrays to keep track of each inning's score throughout the game and uses For...Next loops to traverse arrays to set and get particular values of an array's elements. It also uses arrays with a ListBox to present a team's roster and to display which player is now at bat.
To use the program, users pick the team now at bat by clicking the appropriate OptionButton at the left of the form. Then users can select the current player from a ListBox that lists the players on the team. At the end of an inning, users enter the inning number and the number of runs scored into two TextBoxes at the bottom of the form. Then users click the Add Runs button to display the runs scored during the inning and the total score in the appropriate scoreboard and total score Label controls (see Figure 11.13).
FIGURE 11.13 The Baseball ScoreKeeper program can be found at http://www.mcp.com/ info.
The bulk of the work in the Baseball ScoreKeeper program takes place within the code of two event procedures, Form_Load() and cmdAddRun_Click().
How the Form_Load() procedure initializes the program
Listing 11.6 shows these steps within the code of the Form_Load() event procedure.
01 Private Sub Form_Load()
02 `=====================STEP ONE====================
03 Dim i% `Counter variable 04 Dim TotalScore%
05 Dim InningsString$ `String to display score for inning
06 Dim TeamOneRoster$() `Array to hold players' names
07 Dim TeamTwoRoster$() `Array to hold players' names
08 `Redimension the global score arrays
09 `DEFAULT_INNINGS is a constant declared in the module,
10 `modBaseBall
11 ReDim gTeamOneInnings(DEFAULT_INNINGS - 1)
12 ReDim gTeamTwoInnings(DEFAULT_INNINGS - 1)
13
14 `=====================STEP TWO====================
15 `Initialize the default score for Team One
16
17 TotalScore% = 0
18 For i% = 0 To DEFAULT_INNINGS - 1
19
20 InningsString$ = InningsString$ _
& CStr(gTeamOneInnings(i%)) & " | "
21 Next i%
22
23 `Display the concatenated string in the score label
24 lblTeamOne.Caption = InningsString$
25 `Display the total score for Team One
26 lblTeamOneScore.Caption = CStr(TotalScore%)
27
28 `Clean out score string for new trip through
29 `Team Two's score
30 InningsString$ = ""
31
32 `Initialize the default score for Team Two
33 For i% = 0 To DEFAULT_INNINGS - 1
34 InningsString$ = InningsString$ _
& CStr(gTeamTwoInnings(i%)) & " | "
35 Next i%
36 `Display the concatenated string in the score label
37 lblTeamTwo.Caption = InningsString$
38 `Display the total score for Team Two
39 lblTeamTwoScore.Caption = CStr(TotalScore%)
40 `=====================STEP THREE====================
41 `Make room in the roster arrays for 9 players
42 ReDim TeamOneRoster$(8) `Array elements begin at zero
43 ReDim TeamTwoRoster$(8)
44
45 `Add the players for Team One to the roster array
46 TeamOneRoster$(0) = "Phillips, lf"
47 TeamOneRoster$(1) = "Palmero, cf"
48 TeamOneRoster$(2) = "Erstad, 1b"
49 TeamOneRoster$(3) = "Hollins, 3b"
50 TeamOneRoster$(4) = "Salmon, rf"
51 TeamOneRoster$(5) = "Leyritz, dh"
52 TeamOneRoster$(6) = "Garne, c"
53 TeamOneRoster$(7) = "Gerbeck, 2b"
54 TeamOneRoster$(8) = "DiScensa, ss"
55
56 `Add the players for Team Two to the roster array
57 TeamTwoRoster$(0) = "Garciaparra, ss"
58 TeamTwoRoster$(1) = "Valentibn, 3b"
59 TeamTwoRoster$(2) = "Vaughn, 1b"
60 TeamTwoRoster$(3) = "Jefferson, dh"
61 TeamTwoRoster$(4) = "Cordero, lf"
62 TeamTwoRoster$(5) = "O'Leary, rf"
63 TeamTwoRoster$(6) = "Mack, cf"
64 TeamTwoRoster$(7) = "Hittenberg, c"
65 TeamTwoRoster$(8) = "Frey, 2b"
66
67 `=====================STEP FOUR====================
68 `Traverse the roster arrays and add the contents
69 `the the roster listboxes.
70 For i% = 0 To 8
71 lstTeamOne.AddItem (TeamOneRoster(i%))
72 lstTeamTwo.AddItem (TeamTwoRoster(i%))
73 Next i%
74
75 End Sub
The cmdAddRun_Click() event procedure is the code that adds the runs scored in a given inning to the Scoreboard when the user clicks the Add Runs button.
How the cmdAddRun_Click() procedure works
Using IsNumeric()IsNumeric() is a Visual Basic function that checks a string number to see whether it looks like a number. If the string looks like a number, IsNumeric() returns True; otherwise, it returns False. IsNumeric() is often used to validate user input.
Listing 11.7 shows the event procedure for the cmdAddRuns_Click event.
01 Private Sub cmdAddRun_Click()
02 `=====================STEP One====================
03 Dim CurrentInning%
04 Dim CurrentScore%
05 Dim i%
06 Dim TotalScore%
07 Dim InningsString$
08
09 `=====================STEP TWO====================
10 `Convert the text in the txtInning to an Integer if
11 `indeed the text looks like a number
12 If IsNumeric(txtInning.Text) Then
13 CurrentInning% = CInt(txtInning.Text)
14 Else
15 CurrentInning% = 1
16 End If
17
18 `Make sure the inning number is not more than 9
19 If CurrentInning% > DEFAULT_INNINGS Then
20 CurrentInning% = DEFAULT_INNINGS
21 End If
22
23 `Convert the text in the txtRuns to an Integer if
24 `indeed the text looks like a number
25 If IsNumeric(txtRuns.Text) Then
26 CurrentScore% = CInt(txtRuns.Text)
27 Else
28 CurrentScore% = 0
29 End If
30 `=====================STEP THREE===================
31 `Set the score to the designated inning for the team
32 `identified by the check option box.
33 If opTeamOne.Value = True Then
34 gTeamOneInnings(CurrentInning% - 1) = CurrentScore%
35 Else
36 `If TeamOne.Value is not true, then TeamTwo.Value must
37 `be True. It's a logic thing!
38 gTeamTwoInnings(CurrentInning% - 1) = CurrentScore%
39 End If
40
41 `Set the new score for Team One
42 For i% = 0 To DEFAULT_INNINGS - 1
43 TotalScore% = TotalScore% + gTeamOneInnings(i%)
44 InningsString$ = InningsString$ _
& CStr(gTeamOneInnings(i%)) & " | "
45 Next i%
46 `=====================STEP FOUR===================
47 `Display the concatenated string in the score label
48 lblTeamOne.Caption = InningsString$
49 `Display the total score for Team One
50 lblTeamOneScore.Caption = CStr(TotalScore%)
51
52 `Clean out score string for new trip through
53 `Team Two's score
54 InningsString$ = ""
55 `Clean out the total score integer variable
56 TotalScore% = 0
57
58 `Set the new score for Team Two
59 For i% = 0 To DEFAULT_INNINGS - 1
60 TotalScore% = TotalScore% + gTeamTwoInnings(i%)
61 InningsString$ = InningsString$ _
& CStr(gTeamTwoInnings(i%)) & " | "
62 Next i%
63
64 `Display the concatenated string in the score label
65 lblTeamTwo.Caption = InningsString$
66 `Display the total score for Team One
67 lblTeamTwoScore.Caption = CStr(TotalScore%)
68
69 End Sub
The last thing that the program does is report who is at bat. This occurs in the Click event of the ListBox for each team's roster whenever the user selects a player. Listing 11.8 shows the code for Team One's ListBox Click event procedure. This code uses the List and ListIndex properties that you learned about in the section "Selecting Items from a List."
01 Private Sub lstTeamOne_Click()
02 `Have the name that the user clicks appear in the
03 `at bat label
04 lblTeamOneAtBat.Caption = lstTeamOne.List(lstTeamOne.ListIndex)
05 End Sub
The only difference between the lstTeamOne_Click and lstTeamTwo_Click event procedures is that the first references the Team One at bat Label and ListBox, and the other references the Team Two at bat Label and ListBox.
Some potential problems still exist:
You can easily solve these and other problems; for the most part, you possess the tools you need to address them. All that's required is a little thought and some experimentation.
© Copyright, Macmillan Computer Publishing. All rights reserved.