470 likes | 661 Views
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.
E N D
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.
Using Control Arrays • A control array is group of the same type control which isassigned 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.
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****
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 withit
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
VB Code Box 6-2Code 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 Select End Sub
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
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 If End Sub
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
VB Code Box 6-4Clear OptTypes Option Buttons Private Sub cmdClear_Click() For Counter = 0 to 2’Clear option buttons OptTypes(Counter).Value = False Next End Sub
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
Using List Arrays • To be used in Visual Basic, an arraymust 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
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
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
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 Integer intNumPrices = CInt(InputBox("How many prices?")) For intCounter = 0 To intNumPrices - 1 curPrices(Counter) = CCur(InputBox("Next price:")) Next End Sub
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 Form intCounter =0 Do Until EOF (n) Input #n, ArrayName(Counter) intCounter=intCounter+1 Loop
VB Code Box 6-7Code to Input Array Elements from a File Open “A:\chapter6\prices.txt" For Input As #5’open text file Do Until EOF(5)’ repeat loop until EOF Input #5, Prices(NumPrices)’Prices is array,Numprices is counter intNumPrices = intNumPrices + 1 ‘add 1 to counter Loop Close #5
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
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
VB Code Box 6-8Compute the Sum and Average in Array Private Sub CmdSumAverage_Click() Dim curSum as Currency ’Sum variable Dim intCounter as Integer ’counter variable Dim curAverage as Currency ’Average variable curSum = 0 ’Set sumto 0 For intCounter = 0 to intNumPrices - 1 curSum = curSum + curPrices(intCounter) ’add prices Next If intNumPrices >0 then ’check to see if >0 curAverage = curSum/intNumPrices ’true average prices Else ’if false MsgBox "No values to average!” ’display Msgbox Exit Sub End If txtSum.Text=Format(curSum, “currency”) txtAverage.Text = Format (curAverage, “currency”
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 item If item in list > largest value then Largest value = item in list End decision End repeat Display largest value End procedure
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
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
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
VB Code Box 6-9Displaying the Collating Sequence Private Sub Form_Load() Dim intCounter As Integer For intCounter = 0 To 255 Debug.Print Chr(intCounter); Next End Sub
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 modified • Input #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.
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”)
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
Pseudocode to Find Price for Part Identifier • Begin procedure to find part identifier • Input part identifier • Set Flag to False • Repeat for each part in parts list • If part identifier = identifier on parts list then • Flag = True • Save index of part identifier on parts list • End decision • End repeat • If Flag = True • Use saved index to display part identifier and price • Else • Display message that part not on parts list • End decision • End procedure
VB Code Box 6-11 Find Price for Part ID • Private Sub cmdFind_Click() • Dim intCounter As Integer, intResults As Integer, strFindID as String • Dim blnFound As Boolean ’flag variable • Dim intPriceIndex as Integer • strFindPartID = InputBox("Input part identifier to find")’input Part ID • blnFound = False ’flag set to false • For intCounter = 0 To intNumPrices - 1 • If UCase(strFindPartID) = UCase(strPartId(intCounter)) Then ’if match • blnFound = True ’flag set to True • intPriceIndex = intCounter ‘Save index of PartId on parts list • Exit For ’jump out of loop • End If • Next • If blnFound Then ’if a match is found display PartID and price • txtFound.Text = strPartId(intPriceIndex) & " " & _ • Format(curPrices(intPriceIndex), "Currency") • Else ’ no match found display the message box • Results = MsgBox("Part not found", VbExclamation, "Price Search") • End If • End Sub
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”
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
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 price Private 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
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
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
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)
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 file End Sub
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 1st • position. 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.
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
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 If End Sub
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 Next End Sub *Clicking on a title that appears will give you title, price and location
VB Code Box 6-17cmdBack_Click Event Procedure Private Sub cmdBack_Click() txtSearch.Text = "" lstVideos.Clear ’Clear list box frmVideos.Hide ’Hide video form End Sub
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 Currency Reason 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
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 Integer Dim 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 intProduct End Sub
Using the Step Commands Stepout of Step into The Step Commands Step Over If you select Step Into, you can “step” through the code, line by line and note the result of the code in the various windows--Watch, Locals, or Immediate. You will be asked to identify one of these buttons in a test****