Top Banner
Chapter Six: Working With Arrays in Visual Basic
47

Chapter Six: Working With Arrays in Visual Basic

Jan 02, 2016

Download

Documents

Chapter Six: Working With Arrays in Visual Basic. Objectives for Chapter Six. * Understand the use of control, list, and table arrays in Visual Basic * Use control arrays to work with groups of controls using a single name. - PowerPoint PPT Presentation
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Chapter Six:  Working With Arrays in Visual Basic

Chapter Six: Working With Arrays in Visual Basic

Page 2: Chapter Six:  Working With Arrays in Visual Basic

Objectives for Chapter Six

* Understand the use of control, list, and table arrays in Visual Basic * Use control arrays to work with groups of controls using a single name.* Describe the difference between arrays and combo boxes, list boxes, and similar controls.* Declare the maximum number of elements or rows and columns for an array.* Understand the errors that can occur from exceeding the declared upper limits on index values.* Input data into an array from the keyboard or files using loops.* Manipulate array data to find the sum and average of array values, the largest or smallest value in an array, or to find a particular value.* Work with multiple arrays to match values in one array to those in the other.* Output the result of array processing to a control, the printer, or the Immediate window.* Use Step operations to step though an array operation to find and correct an error.

Page 3: Chapter Six:  Working With Arrays in Visual Basic

Using Control Arrays

• A control array is group of the same type control which is assigned a single name****

• The individual controls are identified by the control array name and an index value starting with 0.****

• The Case decision structure can be useful in working with a control array.

• To create a control array, just enter the same name for more than one control and replay “yes” to the query.

• The order in which the controls are entered determines the index values for the controls in the control array.

Page 4: Chapter Six:  Working With Arrays in Visual Basic

Check Boxes Vs. Option Buttons

• Check box is used to make multiple selections from a list

• Prefix is chk

• Option button is used to make one selection from a list.– Often referred to as radio buttons

• Prefix is opt• Be able to identify this control from a listing of controls****

Page 5: Chapter Six:  Working With Arrays in Visual Basic

Frame Control

• Option buttons must be within a frame control which acts as a container .

• Frames have a prefix of fra.

• Recommendation is to add frame first and add the option button by drawing it in, not double clicking

• All option buttons will have the same name but a different Index, such as optDemo(0), optDemo(1), optDemo(2)

• If the frame is moved, option buttons will move with it

Page 6: Chapter Six:  Working With Arrays in Visual Basic

Option Button Array

• Double click any option button to open the code window and it will have event similar to this

Private Sub optDemo_Click(Index as Integer)

• The Index value is being passed to the event procedure, in other words, the index of the option button that was clicked is now known to the event procedure

• The Index value is used is Select Case statements

Page 7: Chapter Six:  Working With Arrays in Visual Basic

VB Code Box 6-2

Code for Option Buttons

Private Sub optDemo_Click(Index As Integer) Select Case Index Case 0 MsgBox "Button One selected" Case 1 MsgBox "Button Two selected" Case 2 MsgBox "Button Three selected" End SelectEnd Sub

Page 8: Chapter Six:  Working With Arrays in Visual Basic

Check Box Control Array

• All check boxes will have the same name but a different Value, such as chkSelect(0).Value, chkSelect(1).Value, chkSelect(2).value

• The Value will either be True or False. It is True if the check box is selected and False if not selected

• To determine if it is False use the Not operator• Code on Next slide is used to check if a value is

True or False

Page 9: Chapter Six:  Working With Arrays in Visual Basic

VB Code Box 6-1Code for Check Box Control Array

Private Sub cmdSelect_Click() If chkSelect(0).Value And Not chkSelect(1).Value Then MsgBox "Box One selected" ElseIf Not chkSelect(0).Value And chkSelect(1).Value Then MsgBox "Box Two selected" ElseIf chkSelect(0).Value And chkSelect(1).Value Then MsgBox "Boxes One and Two selected" Else MsgBox "No boxes selected" End IfEnd Sub

Page 10: Chapter Six:  Working With Arrays in Visual Basic

VB Code Box 6-3Select Prices Using Option Buttons

(Vintage Video)Private Sub OptTypes_Click(Index As Integer) Dim curPrice As Currency Select Case Index Case 0’Kids curPrice = 0.99 Case 1’Regular curPrice = 1.99 Case 2’Classic curPrice = 2.99 End Select txtVideoPrice.text = Format(curPrice, "currency")End Sub

Page 11: Chapter Six:  Working With Arrays in Visual Basic

VB Code Box 6-4Clear OptTypes Option Buttons

Private Sub cmdClear_Click()For Counter = 0 to 2’Clear option buttons OptTypes(Counter).Value = FalseNextEnd Sub

Page 12: Chapter Six:  Working With Arrays in Visual Basic

Using List Arrays

Arrays are lists or tables of data which have single name. They provide a way of working with long lists in memory versus working with short lists in a list or combo box

Arrays can only store one type of data

Individual array elements are identified by the array name and one or more subscripts or index values. For instance:

curPrices(0), curPrices(1), curPrices(2)

The index must be an integer constant, variable or expression

Page 13: Chapter Six:  Working With Arrays in Visual Basic

Using List Arrays

• To be used in Visual Basic, an array must be declared just like any other variable.

• Arrays can be fixed size or dynamic size (we use only fixed arrays.)– Fixed size-array- specific amount of memory

set aside for it– Dynamic array - no fixed amount of memory

Page 14: Chapter Six:  Working With Arrays in Visual Basic

Using List Arrays

• Form of array declaration

Dim ArrayName (max index value) as variable type

Dim curPrices(9) as Currency

– Above statement allows for 10 values to be stored (0-9)

• The declaration statement defines the upper limit but by default the lower limit on an array index is zero but this can be changed to one or any other value.

• It is not possible to exceed the upper limit or go below the lower limit on the array index values . Will receive a “Subscript out of range” error

Page 15: Chapter Six:  Working With Arrays in Visual Basic

Entering Event Driven Array Data Most of the time you want to input multiple values into an array.Arrays can be input with any of the three types of loops discussed earlier--event driven, for-next, or while/until loops.

If input is from a keyboard and you don’t know the values to be input, an event driven loop is most appropriate. Similar to loops in Chapter 5 except values are entered directly in an array versus being added to a list box. Values don’t need to be summed immediately.

Index for the array corresponds to the value of the counting variable for each value that is input

With an event driven loop, each click of a button increments a counter and inputs the corresponding array element

Page 16: Chapter Six:  Working With Arrays in Visual Basic

Input Using For-Next Loops• With a For-Next loop, you must input the number of arrays

elements. The array values must be input with an Inputbox with the For-Next counter variable matching the array index

• VB Code Box 6-6.Private Sub Input_Click()Dim intCounter As IntegerintNumPrices = CInt(InputBox("How many prices?"))For intCounter = 0 To intNumPrices - 1 curPrices(Counter) = CCur(InputBox("Next price:"))NextEnd Sub

Page 17: Chapter Six:  Working With Arrays in Visual Basic

Code to Input Array from Files

With an Do Until loop, you can input from a file. Increment a counter that matches the index for the array element.

Do Until Loop General FormintCounter =0Do Until EOF (n)

Input #n, ArrayName(Counter)intCounter=intCounter+1

Loop

Page 18: Chapter Six:  Working With Arrays in Visual Basic

VB Code Box 6-7Code to Input Array Elements from a File

Open “A:\chapter6\prices.txt" For Input As #5’open text fileDo Until EOF(5)’ repeat loop until EOF Input #5, Prices(NumPrices)’Prices is array,Numprices is counter intNumPrices = intNumPrices + 1 ‘add 1 to counterLoopClose #5

Page 19: Chapter Six:  Working With Arrays in Visual Basic

Processing Arrays• Typical array operations include summing and averaging the array values and finding the largest or smallest value in the array. •Working with arrays usually involves a For-Next loop. •Summing Prices array elements involves using a statement of the form: Sum = Sum + Prices(Counter)

• Averaging Prices array elements involves dividing the Sum by the number of elements

Page 20: Chapter Six:  Working With Arrays in Visual Basic

Processing Arrays

• Finding the largest or smallest value involves multiple comparisons of array elements.

• To find the maximum Price, you must compare each array value to the current highest price; if it is higher, it becomes the highest price. Do this using For-Next loop and If-then

Page 21: Chapter Six:  Working With Arrays in Visual Basic

VB Code Box 6-8Compute the Sum and Average in ArrayPrivate Sub CmdSumAverage_Click()Dim curSum as Currency ’Sum variableDim intCounter as Integer ’counter variableDim curAverage as Currency ’Average variablecurSum = 0 ’Set sum to 0For intCounter = 0 to intNumPrices - 1

curSum = curSum + curPrices(intCounter) ’add pricesNextIf intNumPrices >0 then ’check to see if >0 curAverage = curSum/intNumPrices ’true average pricesElse ’if false MsgBox "No values to average!” ’display Msgbox Exit SubEnd IftxtSum.Text=Format(curSum, “currency”)txtAverage.Text = Format (curAverage, “currency”

Page 22: Chapter Six:  Working With Arrays in Visual Basic

Pseudocode to Find Maximum Value

Begin procedure to find largest value Set largest value to first item in list

Repeat beginning with second item to last itemIf item in list > largest value then

Largest value = item in listEnd decision

End repeatDisplay largest value

End procedure

Page 23: Chapter Six:  Working With Arrays in Visual Basic

VB Code Box 6-10 Find Maximum Value in List

Private Sub cmdFindMax_Click()’Declare variables and set largest value to first item in the array Dim intCounter As Integer, curLargest As Currency curLargest = curPrices(0) For intCounter = 1 To intNumPrices - 1 If curPrices(intCounter) >curLargest Then ’if item >largest # curLargest = curPrices(intCounter) ’ replace it if it is larger End If Next’Display largest number as currency txtMaxPrice.Text = Format(curLargest, "currency")End Sub

Page 24: Chapter Six:  Working With Arrays in Visual Basic

Code to Find Minimum Value in List

Private Sub cmdFindMax_Click()’Declare variables and set smallest value to first item in the array Dim intCounter As Integer, curSmallest As Currency curSmallest = Prices(0) For intCounter = 1 To intNumPrices - 1 If curPrices(intCounter) > curSmallest Then ’if item > smallest # curSmallest = Prices(Counter) ’ replace if it is smaller End If Next’Display smallest number as currency txtMaxPrice.Text = Format(curSmallest, "currency")End Sub

Page 25: Chapter Six:  Working With Arrays in Visual Basic

Find the Largest/Smallest String Value in a List

• Collating Sequence - order in which characters are displayed

• Digits come before alphabetic characters.

• Upper case A is smaller than uppercase B because it comes first in alphabetical ordering

• Lower case letters come after upper case letters

• Chr() function converts Integer values of the For-Next variable into the corresponding characters

• To reverse operation use the ASC() function with the character as the argument

Page 26: Chapter Six:  Working With Arrays in Visual Basic

VB Code Box 6-9

Displaying the Collating Sequence

Private Sub Form_Load() Dim intCounter As Integer For intCounter = 0 To 255 Debug.Print Chr(intCounter); NextEnd Sub

Page 27: Chapter Six:  Working With Arrays in Visual Basic

Finding Items and Working with Multiple Lists

•The goal of the project is to find a specified part ID and display the part identifier and the price of the part

•To input both the part identifiers and a price a second array, PartID needs to be declared as a string in the Form General declaration section

Dim strPartId(25) as String

•The Input Statement in the Form-Load event must be modifiedInput #5, strPartID(intNumPrices), curPrices(intNumPrices)

•For a given part, the index values or the strPartId, and the curPrices arrays are the same. The index acts as a link between them.

Page 28: Chapter Six:  Working With Arrays in Visual Basic

The Continuation Character

To display the two items in a text box it will be necessary to modify the cmdDisplay event procedure and it will require a long line of code.

Must use the _ (continuation character). There must be a space before this character

The line below add PartsId and price to a list box and formats the price as currency.

lstParts.AddItem PartId(counter) + “ “ _& Format(Prices(Counter), “currency”)

Page 29: Chapter Six:  Working With Arrays in Visual Basic

Flag Variables

• A flag variable is often used to indicate whether a match was found

• It is a Boolean data type, so it has a value of True or False

• The Flag variable must be set to False before the For-Next loop is started

• If the loop finds a match between the PartId that was input and a PartId on the parts list, the Flag is set to TRUE,

• The program jumps out of the loop through the use of the Exit For statement and saves the index of the PartID. The appropriate text box is then updated, otherwise a message box will appear

Page 30: Chapter Six:  Working With Arrays in Visual Basic

Pseudocode to Find Price for Part Identifier

Begin procedure to find part identifierInput part identifier Set Flag to FalseRepeat for each part in parts list

If part identifier = identifier on parts list thenFlag = TrueSave index of part identifier on parts list

End decisionEnd repeatIf Flag = True

Use saved index to display part identifier and price Else

Display message that part not on parts listEnd decision

End procedure

Page 31: Chapter Six:  Working With Arrays in Visual Basic

VB Code Box 6-11 Find Price for Part IDPrivate Sub cmdFind_Click()

Dim intCounter As Integer, intResults As Integer, strFindID as String

Dim blnFound As Boolean ’flag variableDim intPriceIndex as IntegerstrFindPartID = InputBox("Input part identifier to find")’input Part ID

blnFound = False ’flag set to falseFor intCounter = 0 To intNumPrices - 1

If UCase(strFindPartID) = UCase(strPartId(intCounter)) Then ’ if match

blnFound = True ’flag set to TrueintPriceIndex = intCounter ‘Save index of PartId on parts list

Exit For ’jump out of loopEnd If

Next

If blnFound Then ’ if a match is found display PartID and pricetxtFound.Text = strPartId(intPriceIndex) & " " & _Format(curPrices(intPriceIndex), "Currency")

Else ’ no match found display the message boxResults = MsgBox("Part not found", VbExclamation, "Price Search")

End IfEnd Sub

Page 32: Chapter Six:  Working With Arrays in Visual Basic

More on Message Boxes

• The Msgbox can be used as a function by including multiple parameters within parentheses.

• Syntax: Variable=MsgBox (message, buttons,title)

– buttons=one or more VB constants in table 6-3

– title= title (caption)string for the dialog box

• Example:

MsgBox “Part not found”, vbExclamation, “Price Search”

Page 33: Chapter Six:  Working With Arrays in Visual Basic

More on Message Boxes (con’t)

• Msgbox function returns a value which can be checked to determine which button was clicked

• For instance:

intResults= MsgBox (“Write over old file?”,vbYesNoCancel)

Produces a Message Box with 3 buttons Yes, No, and Cancel

Clicking Yes will return a value of 6, No a value of 7, and Cancel a value of 2

Page 34: Chapter Six:  Working With Arrays in Visual Basic

VB Code Box 6-12Save Index for Highest Price Part

Modify cmdFindMax button add a statement that stores the index of the current largest price to the loop that searches for the maximum pricePrivate Sub cmdFindMax_Click() Dim intCounter As Integer, curLargest As Currency, intMaxIndex as Integer curLargest = curPrices(0) For intCounter = 1 To intNumPrices - 1 If curPrices(intCounter) > curLargest Then curLargest = curPrices(intCounter) intMaxIndex = intCounter End If Next txtMaxPrice = strPartId(intMaxIndex) & " " & _ Format(curPrices(intMaxIndex), “currency") End Sub

Page 35: Chapter Six:  Working With Arrays in Visual Basic

Working with Multiple Forms (Vintage Video)

It is possible to have multiple forms in a project.

Add a form by clicking Project/AddForm or click on the Add Form icon on the toolbar .

A blank form replaces the existing form and the form name is added to Project Explorer window

Page 36: Chapter Six:  Working With Arrays in Visual Basic

Working with Multiple Forms (Vintage Video)

• To display a form and load it into memory, use formname.Show **** Example: frmVideos.Show• To hide the form, but not unload it from memory use • formname.Hide. If a control on one form is referred to on another form, the

form name must be included as a part of the control reference.

• Create the frmVideos form. In addition three arrays will be needed. Declare variables for curVideoPrice, strVideoName, strVideoLoc on new form (Figure 6-17)in General Declarations

Page 37: Chapter Six:  Working With Arrays in Visual Basic

Declare Arrays for frmVideos (Figure 6-17)

Dim striVideos(100) as String, intNumVideos as Integer

Dim curVideoPrice(100) as Currency, strVideoLoc(100) as String

_____________________________________________

After entering above code you would create a file called videos.txt, that contains the video name, video price, and video location

Entries in the file must be in the same order as variables are input , i.e. “Ghost”, 1.99,”Drama”

Next update the Form-Load event ( VB Code Box 6-14)

Page 38: Chapter Six:  Working With Arrays in Visual Basic

VB Code Box 6-14frmVideos Form_Load Event Procedure

Private Sub Form_Load() ’Open file for input Open "a:\videos.txt" For Input As #2 Do Until EOF(2)’Input list of videos Input#2,strVideos(intNumVideos), _ curVideoPrice(intnumVideos), _ strVideoLoc(intNumVideos) intNumVideos = intNumVideos + 1’counter Loop Close #2 ’Close fileEnd Sub

Page 39: Chapter Six:  Working With Arrays in Visual Basic

Search in Strings

* To search for a substring within a string, you use the (Instr(string to search, search string) function.

String to search - character string that is being searched for an occurrence of of the second parameter search string

For example: Instr(“Ghostbusters”, “Ghost “) returns 1 because “G” is in the 1stposition. If the character does not exist, Instr returns a zero.

*NOTE: Instr is case sensitive!!!Instr(“Ghostbusters”, “Bust “) will return a value of 0, because Bust in not in Ghostbusters

•To avoid above problem, search for strings using a loop requires that you use •UCase or LCase to convert all strings to the same case before comparisons are•made.

Page 40: Chapter Six:  Working With Arrays in Visual Basic

VB Code Box 6-15 Search for Video Name

Private Sub cmdSearch_Click() Dim strVideoName As String, intCounter As Integer, _ intNumMatches As Integer strVideoName = txtSearch.Text ’Assign value to variable lstVideos.Clear ’Clear list box lstVideos.AddItem "Video Name“ ‘Add string to list box

Page 41: Chapter Six:  Working With Arrays in Visual Basic

VB Code Box 6-15 Search for Video Name (Continued)

For intCounter = 0 To intNumVideos – 1 ’Check all titles If InStr(UCase(strVideos(intCounter)), _ UCase(strVideoName)) > 0 Then intNumMatches = intNumMatches + 1 ’Count number of matches lstVideos.AddItem Videos(Counter)’add item to list box End If Next If intNumMatches = 0 Then ’if no matches are found MsgBox ("No matching videos found! Try again.")’display message ElseIf intNumMatches <= 5 Then ’<=5 matches display in list box lstVideos.AddItem Str(intNumMatches) & " videos found" Else lstVideos.Clear ’Clear list box when OK is clicked MsgBox ("Too many matching videos!")’Display this message End IfEnd Sub

Page 42: Chapter Six:  Working With Arrays in Visual Basic

VB Code Box 6-16Search for Exact Match of Video Name

Private Sub lstVideos_Click() Dim strVideoName As String, intCounter As Integer strVideoName = lstVideos.Text lstVideos.Clear For intCounter = 0 To intNumVideos - 1 If strVideoName = strVideos(intCounter) Then lstVideos.AddItem strVideoName & " " & _ Format(curVideoPrice(intCounter), "currency") & _ " " & strVideoLoc(intCounter) Exit For End If NextEnd Sub*Clicking on a title that appears will give you title, price and location

Page 43: Chapter Six:  Working With Arrays in Visual Basic

VB Code Box 6-17cmdBack_Click Event Procedure

Private Sub cmdBack_Click() txtSearch.Text = "" lstVideos.Clear ’Clear list box frmVideos.Hide ’Hide video formEnd Sub

Page 44: Chapter Six:  Working With Arrays in Visual Basic

Two-Dimensional Arrays

To declare a two-dimensional array (a table) you must provide the maximum row index and the maximum column index. Row and column indexes begin at 0

General form Dim ArrayName(max row index, max column index)as var type Dim sngNumberTable(10,20) as Single

In this example, it will hold 231 elements (11*21)The table on the next slide will be declared as

Dim curRevenue(2,3) as CurrencyReason it has 3 rows (0,1,2) and 4 columns (0,1,2,3)

Each element of the table is defined by its row and column position

Page 45: Chapter Six:  Working With Arrays in Visual Basic

Table 6-6 Product Revenue by Region

(Row,Column)Product Northeast

Column 0

SouthEast

Column 1

Midwest

Column 2

West

Column 3

PC’s

Row 0

53.5

0,0

62.1

0,1

27.1

0,2

41.5

0,3

Storage

Row 1

24.7

1,0

23.5

1,1

27.3

1,2

20.3

1,3

Memory

Row 2

15.1

2,0

11.3

2,1

17.9

2,2

20.7

2,3

Page 46: Chapter Six:  Working With Arrays in Visual Basic

VB Code Box 6-19Form_Load event procedure to Input Data for Two Dimensional Array

Private Sub Form_Load() Dim intProduct As Integer, intRegion As IntegerDim curRevenue(10,10) as Currency Open "a:\chapter6\revenue.txt" For Input As #10 For intProduct = 0 To 2 For intRegion = 0 To 3 Input #10, curRevenue(intProduct, intRegion) Next intRegion Next intProductEnd Sub

Page 47: Chapter Six:  Working With Arrays in Visual Basic

Using the Step Commands

The Step CommandsStep into Stepout of

Step Over

If you select Step Into, you can “step” through thecode, line by line and note the result of the code in thevarious windows--Watch, Locals, or Immediate.You will be asked to identify one of these buttons in a test****