banner



How To Add A Space In Vb Chapter 9


Using Visual Basic 6

Previous chapter Next chapter Contents


- eleven -
Working with Arrays

  • What Is an Assortment?
  • Declaring Arrays
    • Declaring an Array like Declaring a Single Variable
    • Declaring an Array with the To Keyword
  • Changing the Number of Elements in an Array
  • Multidimensional Arrays
    • Using Loops to Traverse an Assortment
  • Adding Items to ListBoxes and ComboBoxes
  • Selecting Items from a List
  • Removing Items from a List
  • Clearing a List
  • Understanding ComboBox Styles
  • Using Arrays, ComboBoxes, and ListBoxes in a Sample Program
  • Examining ScoreKeeper's Upshot Procedures

What Is an Array?

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 exist thought of as a cup that holds an unknown value or an ever changing value (run across Figure 11.one).

FIGURE 11.1 A variable is a placeholder for a specific type of value.

Recall of an assortment, then, as a collection of cups. Each loving cup in the drove can hold the same type of data, and every cup in the drove has the same name. Each cup within the collection is an element and has a number assigned to it that reflects its position inside the collection. The commencement element of an array usually has a position number of 0 (aught).

Arrays can exist different sizes (run across Figure 11.2). One array might accept three elements, another might have thirty elements, and it'due south even possible for an array to have no elements at all--simply the possibility of having elements that are created at a later time.

FIGURE eleven.2 An assortment is a collection of variables.

Declaring Arrays

You can declare, or dimension, an array in 2 means: every bit you would a single variable and past using the To keyword.

Declaring an Array like Declaring a Single Variable

To declare an assortment as y'all would a single variable, yous use the following syntax:

Dim|Public|Private        ArrayName(Subscript) As        DataType      

In this syntax,

  • Dim, Public, and Private are Visual Basic keywords that declare the array and its scope. If you use Dim, the assortment is private to the procedure in which it is alleged. Public makes the array visible from anywhere in the programme, and Private (within the General section of a form or module) makes the array visible but to the grade or module in which it's declared. If you use Dim within a module's procedure, the array will be bachelor to but that process, merely if you lot use Dim in the module's Declarations section, the array will be available to all procedures inside the module.
  • ArrayName is the name of the array.

Option base of operations

When you declare an assortment, the first chemical element of the array is commonly 0 (zero). It'southward possible, however, to forcefulness the first element of an array to be 1. To practice this, insert the argument Choice Base of operations 1 in the General department of a module within your project. You have to do this just when yous want the kickoff element of your array to be element number 1.


  • Subscript is the number of the highest element in the array. Remember that the first element in an array is usually zero, so if you lot declare an array in which Subscript is half dozen, you'll have seven chemical element positions and, therefore, seven elements.
  • As is the Visual Bones keyword that signifies a blazon declaration.
  • DataType is whatever valid Visual Basic data blazon, such equally Integer or Double.

Therefore, to declare an array of integers with five elements in information technology, yous would use the following:

Dim iMyArray(four) As Integer      

To assign a value to each element in the assortment iMyArray, you would use the following:

iMyArray(0) = 9 iMyArray(one) = 342 iMyArray(ii) = 2746 iMyArray(3) = 0 iMyArray(4) = 8901      

To modify the value of the fourth element of the array iMyArray from 0 (zero) to 45, you lot would do as follows:

iMyArray(three) = 45      

To declare an array of ix strings global to your entire plan, you would use the code in Listing 11.1.

List 11.i  11LIST01.TXT--Assigning Values to an Assortment's Elements

01 Public strMyArray(8) As Cord
02
03 strMyArray(0) = "I am a pitcher."
04 strMyArray(1) = "I am a catcher."
05 strMyArray(2) = "I play offset base."
06 strMyArray(3) = "I play 2d base."
07 strMyArray(iv) = "I play third base of operations."
08 strMyArray(5) = "I play shortstop."
09 strMyArray(vi) = "I play left field."  10 strMyArray(seven) = "I play center field."
11 strMyArray(8) = "I play right field."

Declaring an Array with the To Keyword

You lot tin also declare an array by using the To keyword within the subscript syntax. For instance, if you want to create an assortment of 5 Integer variables in which the first element is number 1 and the last element is number v, y'all 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).

Changing the Number of Elements in an Array

Although you usually set the number of elements in an assortment when you lot declare it, it's possible to alter the size of the array. When you lot change the number of elements in an existing array, you redimension it. To practise so, utilise the ReDim keyword in the post-obit syntax:

ReDim [Preserve]        ArrayName(Subscript) Every bit        DataType      

In this syntax,

  • ReDim is the Visual Bones keyword denoting that the array is being redimensioned.
  • Preserve is an optional Visual Basic keyword that forces all pre-existing elements in the assortment to agree their values. If you don't use the Preserve keyword when y'all redimension the array, the value of all elements will be inverse to cipher for numeric data types, and a zero-length string ("") for variable-length strings. Fixed-length strings will exist filled with zeros, and variants volition be initialized to EMPTY, which could be either zero or a zero-length string, depending on the expression.
  • ArrayName is the name of the array.
  • Subscript is the subscript for the highest element in the array.
  • As is the Visual Bones keyword that signifies a type declaration. When redimensioning an array, the Every bit keyword is optional.
  • DataType is any valid Visual Basic data type, such as Integer or Double. When redimensioning an array, the DataType is optional and can't be changed with the Redim keyword unless the array is of blazon Variant.

Using ReDim in your code

The actual implementation of the ReDim statement is different from this conceptual illustration. If y'all create an assortment that you'll later redimension, you can't difficult code the chemical element size of the assortment when you first declare it. Therefore, in practice, the code hither won't redimension the assortment declared in List 11.1.


The following code shows how, conceptually, to redimension the assortment strMyArray (from Listing eleven.i) 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 mode to create an assortment that you'll later redimension.

LISTING 11.two  11LIST02.TXT--Diming an Assortment Without Any Elements Before
ReDiming It

01 `Create an array without any elements
02 Dim strMyArray() as String
03
04 `Dimension the array for 9 elements
05 ReDim strMyArray(viii)
06
07 `Assign values to the assortment elements
08 strMyArray(0) = "I am a bullpen."
09 strMyArray(1) = "I am a catcher."
10 strMyArray(2) = "I play first base of operations."
eleven strMyArray(iii) = "I play second base."
12 strMyArray(4) = "I play third base of operations."
thirteen strMyArray(5) = "I play shortstop."
14 strMyArray(6) = "I play left field."
15 strMyArray(7) = "I play center field."
sixteen strMyArray(8) = "I play correct field."
17
xviii `Add together an element and make information technology so all the values
19 `of the previous elements are kept intact
twenty ReDim Preserve strMyArray(9)
21
22 `Assign a value to the new assortment element
23 strMyArray(ix) = "I am the designated hitter."

Observe in Listing 11.ii that the first ReDim argument (line 5) doesn't use the Preserve keyword. You can practice this because initially at that place 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 desire to lose. If you didn't use the Preserve keyword in the second ReDim argument, strMyArray would have the following values:

strMyArray (0) = "" strMyArray (one) = "" strMyArray (2) = "" strMyArray (iii) = "" strMyArray (four) = "" strMyArray (5) = "" strMyArray (6) = "" strMyArray (vii) = "" strMyArray (8) = "" strMyArray (9) = "I am the designated hitter."      

Remember, arrays are catchy. Be careful!

Multidimensional Arrays

So far, the arrays in this chapter have been one-dimensional arrays--that is, they are a 1-row collection of variables, equally seen in Figure xi.2. In Visual Basic, notwithstanding, you lot can create arrays that accept up to 60 dimensions. Usually, ii-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 ii-dimensional array equally a tic-tac-toe board--a prepare of columns and rows that intersect to class a filigree. Each filigree cell has a location defined as ColumnNumber, RowNumber. Figure eleven.3 is a conceptual illustration of iVar(2,four), a ii-dimensional assortment of integers. Observe that each chemical element is defined by the coordinates of the column position and the row position. For example, the assortment element iVar(0, 0) is 5 and the element iVar(2,two) is 49.

To create a 2-dimensional array, apply the following syntax:

Dim|Public|Individual ArrayName(SubscriptOfCols, _        SubscriptOfRows) As        DataType      

In this syntax,

  • Dim, Public, and Individual are Visual Basic keywords that declare the array and its scope. If y'all utilize Dim, the array is private to the procedure in which information technology'southward declared. Public makes the assortment visible from anywhere in the program, and Private (within a form or module'due south General department) makes the array visible just to the course or module in which it's declared. Using Dim within a module automatically makes the array available anywhere in the program, every bit if the Public keyword were used.
  • ArrayName is the proper noun of the array.
  • SubscriptOfCols is the number of the highest column in the assortment.
  • SubscriptOfRows is the number of the highest row in the array.
  • Equally is the Visual Bones keyword that denotes type declaration.
  • DataType is any valid Visual Basic data blazon.

Figure 11.three Recall of a two-dimensional array as a collection of cups arranged in columns and rows.

Therefore, to declare the assortment shown in Figure 11.3, you would use the following syntax:

Dim iVar(2,4) every bit Integer      

Whereas y'all can consider a two-dimensional array to be a rectangle, you tin can consider a three-dimensional array to be a rectangular block. To declare a three-dimensional assortment of integers, use

Dim iVar(i,2,1) equally Integer      

Effigy 11.four is a conceptual illustration of the iii-dimensional assortment defined in the preceding line.

FIGURE 11.4 A three-dimensional array (one,two,ane) has 12 elements. It's ii columns wide past three rows tall by 2 planes deep.

In the array iVar, the value assigned to each chemical 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(i,i,0) = 55 iVar(1,ii,0) = vii iVar(0,0,1) = 34 iVar(0,i,1) = 13 iVar(0,2,1) = 4500 iVar(1,0,ane) = 612 iVar(1,one,1) = 9 iVar(1,ii,ane) = 784      

Just every bit with a one-dimensional assortment, yous can utilise the To keyword when declaring the subscript range of each dimension in a multidimensional array. Thus, the line

Dim dMyArray(i To 5,  3 To 8,  3 To five) Every bit Double      

would declare a three-dimensional array of Double values, 5 columns wide past six rows tall by three planes deep.

Yous can too employ 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 tin't be changed.

Using Loops to Traverse an Array

You can use the For...Adjacent loop that you learned well-nigh in Chapter x, "Working with Loops," to move through, or traverse, an assortment. This tin 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 list is the event procedure for a button click, in which an array of 20 elements is created. A For...Adjacent loop is used twice--first to assign values to every element in the array, and so to find the value assigned to every element and make a string that reports the value of that chemical element (encounter Figure xi.5).

List 11.3  11LIST03.TXT--Using For...Next Loops to Traverse an Array

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 chemical element in the array
x `by using a loop to traverse to each element
11 `in the assortment.
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
sixteen Next i%
17
eighteen `Create the BeginMsg$ string
19 BeginMsg$ = "The chemical element is: "
twenty MidMsg$ = ", The value is: "
21 `Go through the array again and brand
22 `a string to brandish
23 For i% = 0 To 19
24 LoopMsg$ = LoopMsg$ & BeginMsg$ & CStr(i%)
25 LoopMsg$ = LoopMsg$ & MidMsg$ & iMyArray(i%)
26
27 `Concatenate the loop bulletin to the
28 `full bulletin. As well add together a line break
29 FullMsg$ = FullMsg$ & LoopMsg$ & vbCrLf
30
31 `Clean out the loop message so that
32 `new value side by side fourth dimension through the loop
33 LoopMsg$ = ""
34 Next i%
35
36 txtTraverse.Text = FullMsg$
37 End Sub

FIGURE 11.v This program sets the value of each array element to twice its chemical element number.

The code in Listing 11.3 is simple. Remember that a For...Next loop increments a counting variable equally information technology loops. You assign this counting variable to the element position of the array. And then, set the lower bound of the array (the everyman chemical element number) to the start betoken of the loop and set the upper jump of the array (the highest element number) to the cease betoken of the loop. When you run the loop, the counting variable volition always be at an chemical element of the array.

Adding Items to ListBoxes and ComboBoxes

Of all the standard controls, the ListBox and ComboBox are best suited for categorizing and list information from which users can make choices and selections. These controls are closely related, and the way in which y'all manipulate them is virtually identical. The difference is that the ComboBox combines a ListBox command 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 tin can handle lists. In Visual Basic, a list is an assortment of strings formally referred to with the List belongings. (The List property is common to the ListBox and ComboBox controls.) Near work that yous practise with ListBoxes and ComboBoxes involves calculation and removing strings from the Listing property. Yous tin 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

1. Add together a ListBox or a ComboBox control to the form.
2. Select this control on the course.
three. In the Backdrop window, select the List property (see Effigy xi.6) and type the strings for the List holding in the drop-down box. To add together multiple lines to the List property, printing Ctrl+Enter to add a new line to it (run across Figure 11.7).

At design time, the strings you added to the List property will announced in the ListBox on the class (see Figure xi.eight).

FIGURE xi.6 You can add strings to a ListBox or a ComboBox at blueprint fourth dimension past entering values in the List belongings drop-down list.

FIGURE eleven.7 To add multiple items to a ListBox list at design time, printing Ctrl+Enter.

FIGURE 11.eight You tin view a ListBox's listing at design time.

This pattern-time method for populating the Listing property is useful when your program starts up. Because the contents of a ListBox or ComboBox can alter often while your programme is running, however, you need to be able to add and remove items to and from the List holding while it's running. To practise this, the ListBox and CombBox controls make all-encompassing utilize of the AddItem, RemoveItem, and Articulate methods.

To add together a cord to the Listing of a Listbox or ComboBox during runtime, use the AddItem method, which has the following syntax:

        Object.AddItem        StringToAdd      

In this syntax,

  • Object is the Name holding of the ListBox or ComboBox.
  • AddItem is the Visual Basic keyword for the method.
  • StringToAdd is the string that you want to add to the control's listing.

Listing 11.4 shows you lot how to utilise the AddItem method in a form's Load event procedure to add together strings to the List of a ListBox. Figure 11.ix shows the consequence of the form's Load event.

LISTING 11.4  11LIST04.TXT--Using the AddItem Method to Add Items to a ListBox Control

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 Cease Sub

FIGURE 11.9 You can employ the AddItem method in a form�s Load consequence to initialize the Listing property of a ListBox command.

Selecting Items from a List

To empathise how Visual Basic determines the value of a string selected in the List of a ListBox or ComboBox, you lot demand to empathise that a List is an array of strings. Every bit you lot learned earlier in this chapter, an array is declared as follows:

Dim        ArrayName(Subscript) As        DataType      

Therefore, if y'all declared a 4-element array equally MyArray(three), you would list the elements in that array as follows:

MyArray(0) MyArray(1) MyArray(2) MyArray(3)      

If you desire to determine the value assigned to the second element, you could utilise the following statement (remember, by default the first element is MyArray(0)):

MyValue = MyArray(i)      

The ListBox and ComboBox controls employ a similar format. The property List is the general term that Visual Basic uses to refer to the unabridged array of strings inside a ListBox or ComboBox. Therefore, to notice the value of the second string in the ListBox called lstHero (from Listing 11.4), you would use the post-obit 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 holding. When you select a cord in a ListBox, Visual Basic assigns the position number of that cord to the ListIndex property of the control. Therefore, to determine the value of the selected string in lstHero (from Listing 11.4), you lot would use the following code:

Individual Sub lstHero_Click()     lblHero.Caption = lstHero.List(lstHero.ListIndex) Cease Sub      

This is the upshot 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. Effigy 11.10 shows what happens when the user selects a string.

FIGURE 11.10 Y'all can program the Click, MouseUp, or MouseDown events of a ListBox to detect the value of a user's selection.

A faster way to detect out the value of the cord a user selects in a ListBox or ComboBox is to use the Text property. For example, you tin can utilise the post-obit for a ListBox:

Dim strMyStr every bit Cord strMyStr = List1.Text      

For a ComboBox, utilise the following:

Dim strMyStr as String strMyStr = Combo1.Text      

Removing Items from a List

You remove a string from a listing in a ListBox or ComboBox by using the RemoveItem method:

        Object.RemoveItem        Index      

In this syntax

  • Object is the Proper noun holding of the ListBox or ComboBox.
  • RemoveItem is the Visual Basic keyword for the method used to remove items from a list.
  • Index is the position in the List holding of the string that you desire to remove from the control. To remove a selected item from a list, use the ListIndex property of the control.

Figure 11.xi shows an enhancement to the program presented in Effigy 11.x. A button has been added to remove the string that the user selects from the ListBox. Listing xi.5 shows the RemoveItem method used in code.

LISTING eleven.5  11LIST05.TXT--Using the RemoveItem Method to Remove a Cord
from a ListBox

01 Private Sub cmdRemove_Click()
02 lstHero.RemoveItem (lstHero.ListIndex)
03 lblHero.Caption = ""
04 Terminate Sub

When you remove an detail from a ListBox or ComboBox, make sure that you clear the text from the Caption property of the Label command lblHero, as shown in line 3 of Listing 11.5. If you don't do this, the user volition remove the string from the ListBox, but it volition remain in the Characterization command.

FIGURE 11.11 A CommandButton provides a manner for the user to remove an item from a listing.

Clearing a Listing

If you desire to remove all the strings contained in a ListBox or ComboBox, use the Articulate method:

        Object.Clear      

In this syntax

  • Object is the Proper name holding of the ListBox or ComboBox.
  • Articulate is the Visual Basic keyword for the method that removes all items from a list.

Thus, i line of code tin exist used to clear all the strings in the ListBox of the plan shown in Figure eleven.11:

lstHero.Clear      

Understanding ComboBox Styles

The ListBox and ComboBox controls take much in common, simply each has a distinct apply. A ListBox takes upward more room than a ComboBox, and when using a ListBox, you tin't select or input unlisted information. A ComboBox offers more flexibility and uses a class's space more efficiently.

A ComboBox's Style property enables you to alter the operational characteristics and appearance of the command. Table eleven.ane describes these styles, and Figure 11.12 shows the ComboBox styles practical to a course. You lot tin can too download this code from http://world wide web.mcp.com/info. You volition exist asked for an ISBN. Enter 078971633x and click the Search push to become to the Using Visual Basic half-dozen page.


Using a simple philharmonic ComboBox

When you beginning add a ComboBox with the one - Simple Philharmonic style to a form, the ComboBox is sized so that none of the ListBox is displayed. Increment the Height property to display more than of the ListBox.


TABLE 11.1  Values for the ComboBox Style Property

Setting Description
0 - Drib-downwardly Combo A drop-downwardly listing. Withal, users can as well 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 tin select information from the ListBox or type new data into the TextBox. The size of a simple ComboBox includes both edit and list portions.
2 - Driblet-down Listing A read-only driblet-down list from which users can but select data. Users can't enter data into the command.

FIGURE 11.12 Notice that with a drop-down ComboBox style, you lot tin can add together new data to the command at runtime.

The most mutual ComboBox styles are 0 - Drop-down Combo and 2 - Drop-downward List. As mentioned earlier, you use a drop-down ComboBox mode when you want to let users add new information that's non in the ComboBox'due south list. You use the driblet-downward list style when you want users to cull from data that's only in the drib-down list of the ComboBox.

Using Arrays, ComboBoxes, and ListBoxes in a Sample Program

The Baseball ScoreKeeper plan uses many things you've just learned. It uses arrays to keep rails of each inning's score throughout the game and uses For...Adjacent loops to traverse arrays to prepare and become detail values of an array's elements. It also uses arrays with a ListBox to present a team'south roster and to display which player is now at bat.

To use the program, users pick the squad now at bat by clicking the advisable OptionButton at the left of the grade. Then users tin select the current player from a ListBox that lists the players on the squad. At the end of an inning, users enter the inning number and the number of runs scored into 2 TextBoxes at the bottom of the class. And so users click the Add together Runs push to display the runs scored during the inning and the total score in the advisable scoreboard and total score Label controls (meet Figure 11.13).

FIGURE 11.thirteen The Baseball ScoreKeeper program can be found at http://www.mcp.com/ info .

Examining ScoreKeeper's Effect Procedures

The bulk of the work in the Baseball game ScoreKeeper plan takes place within the code of two result procedures, Form_Load() and cmdAddRun_Click().

How the Form_Load() process initializes the program

1. It declares local variables for scorekeeping and the scoreboard string and declares ane array for each team'due south roster. Finally, it redimensions the two global scorekeeping arrays (these are declared in the module modBaseBall, one for each squad) to nine elements. The elements of these arrays will agree the score for each inning.
two. It uses a For...Next loop to traverse each element in the Squad One scorekeeping array, gTeamOneInnings(). Within each iteration of the loop, it takes the value in each element and adds it to the variable TotalScore%, which holds the total score for all the innings. Then Form_Load converts the value in each element to a character by using the CStr() function and combines this converted grapheme with the | character to form a larger scorekeeping string variable, InningString$ (you'll learn more most this in Chapter 12, "Working with Strings and Typecasting"). Side by side, the value of the InningString$ variable is assigned to the Caption holding of the Scoreboard characterization, and the value of the TotalScore% variable is assigned to the Caption holding of the full runs Label. Finally, the InningString$ variable is reset, and this step is repeated for Team 2.
3. Information technology redimensions the team roster arrays for both teams to take ix elements. Then information technology adds the names and playing positions of each player to the element that corresponds to the player'due south position in the batting club.
four. It uses a For...Adjacent loop with the AddItem method of each team's ListBox to traverse the roster arrays of each team and add the value of each element in the array (player name and playing position) to the respective ListBox.

Listing 11.half-dozen shows these steps inside the code of the Form_Load() issue process.

LISTING xi.6  11LIST.06.TXT--Initializing the Chief Class of the Baseball game
Scorekeeper Awarding with the Form_Load() Result Procedure

01 Individual 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$() `Assortment to hold players' names
08 `Redimension the global score arrays
09 `DEFAULT_INNINGS is a constant alleged in the module,
10 `modBaseBall
11 ReDim gTeamOneInnings(DEFAULT_INNINGS - i)
12 ReDim gTeamTwoInnings(DEFAULT_INNINGS - one)
xiii
14 `=====================STEP TWO====================
15 `Initialize the default score for Team One
xvi
17 TotalScore% = 0
eighteen 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 Squad One
26 lblTeamOneScore.Explanation = CStr(TotalScore%)
27
28 `Make clean out score string for new trip through
29 `Team 2'south score
30 InningsString$ = ""
31
32 `Initialize the default score for Team Ii
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 `Brandish the total score for Squad Ii
39 lblTeamTwoScore.Caption = CStr(TotalScore%)
40 `=====================STEP THREE====================
41 `Brand room in the roster arrays for 9 players
42 ReDim TeamOneRoster$(8) `Array elements begin at cipher
43 ReDim TeamTwoRoster$(viii)
44
45 `Add the players for Squad One to the roster array
46 TeamOneRoster$(0) = "Phillips, lf"
47 TeamOneRoster$(one) = "Palmero, cf"
48 TeamOneRoster$(2) = "Erstad, 1b"
49 TeamOneRoster$(3) = "Hollins, 3b"
50 TeamOneRoster$(4) = "Salmon, rf"
51 TeamOneRoster$(five) = "Leyritz, dh"
52 TeamOneRoster$(half dozen) = "Garne, c"
53 TeamOneRoster$(7) = "Gerbeck, 2b"
54 TeamOneRoster$(8) = "DiScensa, ss"
55
56 `Add together the players for Squad Two to the roster assortment
57 TeamTwoRoster$(0) = "Garciaparra, ss"
58 TeamTwoRoster$(1) = "Valentibn, 3b"
59 TeamTwoRoster$(2) = "Vaughn, 1b"
60 TeamTwoRoster$(three) = "Jefferson, dh"
61 TeamTwoRoster$(4) = "Cordero, lf"
62 TeamTwoRoster$(v) = "O'Leary, rf"
63 TeamTwoRoster$(6) = "Mack, cf"
64 TeamTwoRoster$(7) = "Hittenberg, c"
65 TeamTwoRoster$(8) = "Frey, 2b"
66
67 `=====================Stride 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 Cease 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() process works

one. It creates variables that reflect the current inning and current score. It likewise creates a counter variable and variables that concord the total score and the scoreboard string.

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 similar a number, IsNumeric() returns True; otherwise, it returns Imitation. IsNumeric() is often used to validate user input.


ii. It takes the text entered in the Inning TextBox, inspects it to make sure that it's a number by using the IsNumeric() function, and makes sure that the user didn't enter a number higher than the number of innings in the game so far. If this value is acceptable, the procedure assigns it to the electric current inning variable, CurrentInning%. cmdAddRun_Click() does the aforementioned sort of IsNumeric() check on the text in the Runs Scored TextBox, txtRuns. If this is acceptable, the procedure assigns it to the current score variable, CurrentScore%.
3. The procedure checks the value of the OptionButton for Team One. If the OptionButton is selected, its value will exist True and the value in the electric current score variable, CurrentScore%, volition exist assigned to an chemical element in gTeamOneInnings(), the global array that holds the values for Team One's per-inning score. The current score is assigned to the element position that'due south one less than the value of the electric current inning variable, CurrentInning%. This is because the first element in the gTeamOneInnings array is zero. If the value of the OptionButton for Team One is False, the OptionButton for Team Two must take been selected and this pace should be done in terms of Team Two.
4. It traverses the global arrays that hold the value of every inning's score for each team to make up one's mind the total runs scored for each team. Then the procedure constructs the scoreboard cord and assigns the results to the advisable controls. (This is an exact repeat of the piece of work washed in the fourth footstep of the Form_Load() effect procedure.)

List xi.7 shows the issue procedure for the cmdAddRuns_Click issue.

LISTING 11.7  11LIST07.TXT--Determining the Team and Inning to Which the
Scored Runs Apply

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 `=====================Footstep Ii====================
x `Convert the text in the txtInning to an Integer if
11 `indeed the text looks like a number
12 If IsNumeric(txtInning.Text) Then
xiii CurrentInning% = CInt(txtInning.Text)
14 Else
15 CurrentInning% = 1
16 Terminate If
17
18 `Make sure the inning number is not more than ix
nineteen If CurrentInning% > DEFAULT_INNINGS Then
xx 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) And then
26 CurrentScore% = CInt(txtRuns.Text)
27 Else
28 CurrentScore% = 0
29 End If
xxx `=====================STEP 3===================
31 `Set the score to the designated inning for the team
32 `identified by the bank check choice box.
33 If opTeamOne.Value = Truthful 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% - i) = CurrentScore%
39 End If
40
41 `Set the new score for Team I
42 For i% = 0 To DEFAULT_INNINGS - 1
43 TotalScore% = TotalScore% + gTeamOneInnings(i%)
44 InningsString$ = InningsString$ _
& CStr(gTeamOneInnings(i%)) & " | "
45 Next i%
46 `=====================Footstep FOUR===================
47 `Display the concatenated string in the score characterization
48 lblTeamOne.Caption = InningsString$
49 `Display the full score for Team One
50 lblTeamOneScore.Caption = CStr(TotalScore%)
51
52 `Make 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 `Gear up the new score for Team Ii
59 For i% = 0 To DEFAULT_INNINGS - ane
60 TotalScore% = TotalScore% + gTeamTwoInnings(i%)
61 InningsString$ = InningsString$ _
& CStr(gTeamTwoInnings(i%)) & " | "
62 Adjacent 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 concluding affair that the program does is report who is at bat. This occurs in the Click issue of the ListBox for each team's roster whenever the user selects a player. Listing eleven.8 shows the code for Squad I'southward ListBox Click event procedure. This code uses the List and ListIndex properties that you learned about in the section "Selecting Items from a List."

Listing eleven.8  11LIST08.TXT--Code for the lstTeamOne_Click Procedure

01 Private Sub lstTeamOne_Click()
02 `Have the proper name that the user clicks announced in the
03 `at bat label
04 lblTeamOneAtBat.Explanation = lstTeamOne.List(lstTeamOne.ListIndex)
05 End Sub

The only difference betwixt the lstTeamOne_Click and lstTeamTwo_Click event procedures is that the outset references the Team Ane at bat Characterization and ListBox, and the other references the Team Two at bat Label and ListBox.

Some potential problems nevertheless exist:

  • What happens if the user enters a letter character such equally "a" in the Runs Scored or Inning text box? You lot need to provide an fault check on these text boxes, mayhap using the IsNumeric() function.
  • What if a game goes into extra innings? You need to Redim the scorekeeping arrays.
  • How practice you remind users to change the player at bat if they forget, and what happens if users forget to change the team at bat? You might set a variable that tracks the most recently accessed player or team and provide a message box if this variable matches the new actor or team when the Add Runs push button is clicked.

You lot can easily solve these and other problems; for the most part, you lot possess the tools y'all need to address them. All that's required is a little thought and some experimentation.


Previous chapter Next chapter Contents

© Copyright, Macmillan Computer Publishing. All rights reserved.

How To Add A Space In Vb Chapter 9,

Source: http://lnr.irb.hr/ebooks/078971633X/ch11/ch11.htm

Posted by: aginpegare.blogspot.com

0 Response to "How To Add A Space In Vb Chapter 9"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel