Chapter Six: Working With Arrays in Visual Basic.

Slides:



Advertisements
Similar presentations
1.
Advertisements

Objectives Understand the software development lifecycle Perform calculations Use decision structures Perform data validation Use logical operators Use.
Tutorial 12: Enhancing Excel with Visual Basic for Applications
Programming Logic and Design Sixth Edition
Microsoft Visual Basic: Reloaded Chapter Five More on the Selection Structure.
VBA Modules, Functions, Variables, and Constants
Arrays Array of Controls: several controls, of the same type (Class: a prototype for an object indicating the properties and methods), that have the same.
Repeating Program Instructions Chapter Microsoft Visual Basic.NET: Reloaded 1.
Chapter 5 new The Do…Loop Statement
Chapter 8: String Manipulation
© 1999, by Que Education and Training, Chapter 5, pages of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach.
Processing Arrays Lesson 8 McManusCOP Overview One-Dimensional Arrays –Entering Data into an Array –Printing an Array –Accumulating the elements.
IE 212: Computational Methods for Industrial Engineering
Chapter 4: The Selection Structure
Tutorial 11 Using and Writing Visual Basic for Applications Code
Microsoft Visual Basic 2008 CHAPTER NINE Using Arrays and File Handling.
Microsoft Visual Basic 2005 CHAPTER 9 Using Arrays and File Handling.
Microsoft Visual Basic 2010: Reloaded Fourth Edition Chapter Six Repeating Program Instructions.
Using Arrays and File Handling
Chapter 17: Arrays Spreadsheet-Based Decision Support Systems Prof. Name Position (123) University Name.
Chapter 7 Code Tables. VB Code Box 7-1 Event Procedure for Compute Button Private Sub hsbExemptions_Change() txtExemptions.Text =Str(hsbExemptions.Value)
Chapter 4: The Selection Process in Visual Basic.
Chapter 12: How Long Can This Go On?
Copyright © 2001 by Wiley. All rights reserved. Chapter 5: The Repetition Process in Visual Basic Event Driven Loops Determinate Loops Indeterminate Loops.
The Repetition Process in Visual Basic. The Repetition Process The capability to repeat one or more statements as many times as necessary is what really.
Copyright © 2001 by Wiley. All rights reserved. Chapter 4: The Selection Process in Visual Basic Selection Process Two Alternative Structure If..Then..ElseIf.
Visual Basic.NET Comprehensive Concepts and Techniques Chapter 7 Using Menus, Common Dialogs, Procedures, Functions, and Arrays.
Using Client-Side Scripts to Enhance Web Applications 1.
Arrays and 2D Arrays.  A Variable Array stores a set of variables that each have the same name and are all of the same type.  Member/Element – variable.
© 1999, by Que Education and Training, Chapter 8, pages of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach.
1 Week 6 The Repetition Structure. 2 The Repetition Structure (Looping) Lesson A Objectives After completing this lesson, you will be able to:  Code.
Tutorial 51 Programming Structures Sequence - program instructions are processed, one after another, in the order in which they appear in the program Selection.
Tutorial 6 The Repetition Structure
Microsoft Visual Basic 2008: Reloaded Third Edition Chapter Six The Do Loop and List Boxes.
‘Tirgul’ # 3 Enterprise Development Using Visual Basic 6.0 Autumn 2002 Tirgul #3.
Chapter 5: More on the Selection Structure Programming with Microsoft Visual Basic 2005, Third Edition.
CS285 Visual Basic 2 Department of Computing UniS 1 Statements in Visual Basic A statement is the fundamental syntactical element of a program smallest.
Chapter 16: Programming Structures Spreadsheet-Based Decision Support Systems Prof. Name Position (123) University Name.
Chapter 16: Programming Structures Spreadsheet-Based Decision Support Systems Prof. Name Position (123) University Name.
1.
1 Week 5 More on the Selection Structure. 2 Nested, If/ElseIf/Else, and Case Selection Structures Lesson A Objectives After completing this lesson, you.
Programming Logic and Design Fourth Edition, Comprehensive Chapter 8 Arrays.
Copyright © 2001 by Wiley. All rights reserved. Chapter 6: Using Arrays Control Arrays List Arrays Finding Items in Arrays Multiple Forms 2-Dimensional.
6-1 Chapter 6 Working with Arrays in VB.NET. 6-2 Learning Objectives Understand the use of list and table arrays in VB.NET projects and the difference.
1 Scripting Languages VBScript - Recognized mainly by Internet Explorer only - Netscape does have a plug-in JavaScript - Recognized by Internet Explorer.
Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.
Processing Arrays Lesson 9 McManusCOP Overview One-Dimensional Arrays –Entering Data into an Array –Printing an Array –Accumulating the elements.
Programming with Microsoft Visual Basic 2008 Fourth Edition Chapter Eight String Manipulation.
Programming with Microsoft Visual Basic 2012 Chapter 9: Arrays.
© 2006 Lawrenceville Press Slide 1 Chapter 6 The Post-Test Do…Loop Statement  Loop structure that executes a set of statements as long as a condition.
Controlling Program Flow with Looping Structures
1 Chapter 7 Arrays. 2 Outline and Objective In this chapter we will Learn about arrays One-dimensional arrays Two-dimensional arrays Learn about searching.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Student Grades Application Introducing Two-Dimensional Arrays and RadioButton.
Controlling Program Flow with Decision Structures.
 2002 Prentice Hall. All rights reserved. 1 Chapter 5 – Control Structures: Part 2 Outline 5.1Introduction 5.2 Essentials of Counter-Controlled Repetition.
Clearly Visual Basic: Programming with Visual Basic 2008 Chapter 11 So Many Paths … So Little Time.
Programming Logic and Design Fifth Edition, Comprehensive Chapter 6 Arrays.
Chapter 6 - Visual Basic Schneider1 Chapter 6 Repetition.
Chapter 4.  Variables – named memory location that stores a value.  Variables allows the use of meaningful names which makes the code easier to read.
Visual Basic.NET Comprehensive Concepts and Techniques Chapter 6 Looping and Multiple Forms.
Microsoft Visual Basic 2008: Reloaded Third Edition
Visual Basic 6 (VB6) Data Types, And Operators
The Selection Structure
Chapter 7 Arrays.
Microsoft Visual Basic 2005: Reloaded Second Edition
CIS 16 Application Development Programming with Visual Basic
Introduction to Problem Solving and Control Statements
Language Constructs Construct means to build or put together. Language constructs refers to those parts which make up a high level programming language.
Programming Logic and Design Fifth Edition, Comprehensive
Introduction to Computer Programming IT-104
Presentation transcript:

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.

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.

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 with it

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-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 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-1 Code 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-3 Select 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-4 Clear 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 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

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-7 Code 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-8 Compute 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 sum to 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-9 Displaying 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-12 Save 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-14 frmVideos 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-16 Search 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-17 cmdBack_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

Table 6-6 Product Revenue by Region (Row,Column ) ProductNortheast Column 0 SouthEast Column 1 Midwest Column 2 West Column 3 PC’s Row , , , ,3 Storage Row , , , ,3 Memory Row , , , ,3

VB Code Box 6-19 Form_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 The Step Commands Step into Stepout of 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****