157212 Week 3 lecture 2 Lists, Loops - PowerPoint PPT Presentation

1 / 74
About This Presentation
Title:

157212 Week 3 lecture 2 Lists, Loops

Description:

Simple List Box with/without scroll bars. ComboBox tool. cbo prefix. List may allow for user to add new items. List may 'drop down' to display items in list ... – PowerPoint PPT presentation

Number of Views:27
Avg rating:3.0/5.0
Slides: 75
Provided by: richard754
Category:

less

Transcript and Presenter's Notes

Title: 157212 Week 3 lecture 2 Lists, Loops


1
157212Week 3 lecture 2Lists, Loops Arrays
2
Tutorials start next week
  • See web site for handout
  • www.massey.ac.nz/tsrichar

3
ListBoxes ComboBoxes
  • Provide a list for the user to select from
  • Various styles, choose based on
  • Amount of data to be displayed
  • Space available
  • User's ability to add to the list

4
Types of List Controls
  • ListBox tool
  • 1st prefix
  • Simple List Box with/without scroll bars
  • ComboBox tool
  • cbo prefix
  • List may allow for user to add new items
  • List may "drop down" to display items in list

5
List Controls Visually
Dropdown Combo Box
Simple Combo Box
List Boxes
Dropdown List Box
6
Choosing List Type
  • Many items, little space
  • Dropdown Combo Box
  • Dropdown List
  • Few items
  • List Box
  • User allowed to add to the list
  • Simple Combo Box
  • Dropdown Combo Box

7
Name and Text Properties
  • ListBoxes
  • Name displayed at Design Time
  • Text accessible only at Run Time
  • ComboBoxes
  • Text displayed and accessible at Design Time
  • Text also accessible at Run Time
  • If user enters new data in ComboBox then VB
    stores it temporarily in the Text property

8
DropDownStyle Property
  • Used to indicate the type of ComboBox
  • Dropdown Combo DropDown
  • Simple Combo Simple
  • Dropdown List DropDownList

9
Items Collection
  • List of items in a ListBox or ComboBox is a
    collection
  • Collections are objects that have properties and
    methods that allow you to
  • Add items
  • Remove items
  • Refer to individual items
  • Count items
  • Clear the collection

10
Index Property
  • Zero based value used to reference individual
    items in the collection
  • Position of an item in the list
  • 1st item Index 0 (1-10)
  • 2nd item Index 1 (2-11)
  • 3rd item Index 2 (3-12)
  • So we can say that . . .
  • nth item Index n-1

11
SelectedIndex Property
  • Use to identify currently selected item in the
    list
  • If no item is selected ListIndex -1
  • Use to select an item in the list

12
Items.Count Property
  • Use to determine number of items in the list

Remember Items.Count is the actual number of
items in the list BUT the SelectedIndex property
and Index will be 1 less. For example, it there
are 20 items in the list Items.Count20 BUT
Index 19 for the last item in list
13
Using the Items Collection
  • Use the index of the item to reference a specific
    item in the collection
  • Remember that the index is zero based so the 1st
    item in the list is index position zero

lstUni.Items(5) Massey" ' Next line
references the currently selected
item strSelectedFlavor lstFlavor.Items(lstFlavor
.SelectedIndex)
14
Filling a List Hint on test
  • Design time in properties window
  • Items property
  • Click on ellipses to open String Collection
    Editor
  • Separate items with ENTER key
  • Run time methods
  • Items.Add
  • OR
  • Items.Insert

15
Filling List - Design Time
Click ellipses button to open
16
Items.Add Method
  • Use to add new items to the list at run time
  • General Form
  • Examples

Object.Items.Add(ItemValue)
lstNames.Items.Add("Brandon") lstDeptNums.Items.Ad
d(100) cboMajors.Items.Add(txtMajors.Text) 'Next
line adds new item user typed in to
combo cboGrade.Items.Add(cboGrade.Text)
17
Items.Insert Method
  • Use to add new items to the list at run time at a
    specific location(index) in the collection
  • General Form
  • Examples

Object.Items.Insert(IndexPosition, ItemValue)
lstDeptNums.Items.Insert(1, 100) cboGrade.Items.in
sert(0, "Freshman") cboMajors.Items.Insert(11,
txtMajors.Text)
18
Items.RemoveAt Method
  • Use to specifically remove items from the list at
    run time by specifying the index of the item
  • General Form
  • Examples

Object.Items.RemoveAt(IndexPosition)
lstDeptNums.Items.RemoveAt(1) ' Next line
removes the currently selected item cboGrade.Items
.RemoveAt(cboGrade.SelectedIndex)
19
Items.Remove Method
  • Use to specifically remove items from the list at
    run time by specifying the Text of the item
  • General Form
  • Examples

Object.Items.Remove(TextString)
lstDeptNums.Items.Remove("USC") ' Next line
removes the currently selected item cboGrade.Items
.Remove(cboGrade.Text)
20
Clear Method
  • Empty the entire list from list box or combo box,
    remove all the items
  • General Form
  • Examples

Object.Items.Clear( )
lstDeptNums.Items.Clear( ) cboGrade.Items.Clear( )
21
ListBox and ComboBox Events
  • TextChanged Event
  • Occurs when user types text into Combo
  • ListBox does not have TextChanged Event
  • SelectedIndexChanged Event
  • Enter Event (receive focus)
  • Leave Event (lose focus)

22
Loops
  • Repeating a series of instructions
  • Each repetition is called an iteration
  • Types of Loops
  • Do
  • Use when the number of iterations is unknown
  • For Next
  • Use when the number of iterations known

23
Do Loop
  • Ends based on a condition you specify, either
  • Loop While a condition is True
  • Loop Until a condition becomes True
  • Condition can be located at
  • Top of Loop, Pretest
  • Bottom of Loop, Posttest

24
Do Loop General Form
  • Do While Until condition
  • Statements to execute
  • Loop
  • OR
  • Do
  • Statements to execute
  • Loop While Until condition

Top of Loop Condition, Pretest
Bottom of Loop Condition, Posttest
25
Do's - When Evaluated
  • Top Evaluation, not guaranteed to run once since
    evaluated BEFORE running
  • Do While Loop
  • Do Until Loop
  • Bottom Evaluation, will always run at least one
    time
  • Do Loop While
  • Do Loop Until

26
For Next Loops
  • Use when you know the number of iterations
  • Uses a numeric counter variable, called Loop
    Index, to control number of iterations
  • Loop Index is incremented at the bottom of the
    loop on each iteration
  • Step value can be included to specify the
    incrementing amount to increment Loop Index, step
    can be a negative number

27
For Next Loop General Form
  • For LoopIndex InitialValue To TestValue Step
    Increment
  • Statements to execute
  • Next LoopIndex

28
Do Loops / For Next Loops Deciding Which To Use
29
Manually Exiting For Next Loops
  • In some situations you may need to exit the loop
    prematurely
  • Use the Exit For statement inside the loop
    structure
  • Generally the Exit For is part of an If statement

30
..and then there was CASE
  • Case Arrays

31
Case Structure
  • Best alternative for testing a single variable or
    expression for multiple values
  • Any decisions coded with nested If statements can
    also be coded using Case structure
  • Case Structure is simpler, cleaner, more
    efficient than the nested If

32
Select Case General Form(also notice indenting)
  • Select Case expression
  • Case ConstantList
  • code to run
  • Case ConstantList
  • code to run
  • Case Else
  • code to run
  • End Select

If expressionvalue in constant list
If expressionvalue in constant list
If expressionlt gtvalues in any of the preceding
constant lists
Case Else is an optional clause
33
Select Case - Numeric Value Example 1
  • Select Case intScore
  • Case Is gt 100
  • lblMsg.Text"Excellent Score"
  • Case 80 to 99
  • lblMsg.Text"Very Good"
  • Case 60 to 79
  • lblMsg.Text"Excellent Score"
  • Case Else
  • lblMsg.Text"Improvement Needed"
  • End Select

34
Select Case - Numeric Value Example 2
  • Select Case intListIndex
  • Case 0
  • HandleItemZero( )
  • Case 1, 2, 3
  • HandleItems( )
  • Case Else
  • HandleNoSelection( )
  • End Select

35
Select Case - String Value Example
  • Select Case txtTeam.Text.ToUpper( )
  • Case "TIGERS"
  • (Code for Tigers)
  • Case "LEOPARDS"
  • (Code for Leopards)
  • Case "COUGARS", "PANTHERS"
  • (Code for Cougars and Panthers)
  • End Select

36
Arrays
  • List or series of values all referenced by the
    same name
  • Similar to list of values for list boxes and
    combo boxes - without the box
  • Use an array to keep a series of variables for
    later processing such as
  • Reordering
  • Calculating
  • Printing

37
Array Terms
  • Element
  • Individual item in the array
  • Index (or subscript)
  • Zero based number used to reference the specific
    elements in the array
  • Must be an integer
  • Boundaries
  • Lower Subscript, 0 by default
  • Upper Subscript

38
Simple Array Example
strName Array
39
Defining Arrays
  • Use Dim statement to declare
  • Specify the number of elements in the array as
    the UpperSubscript
  • Each element of the array will be assigned a
    default value
  • Numeric gt 0
  • String gt empty string, 0 characters

40
Defining Arrays - Alternate Form
  • Optionally, the elements in the array may be
    assigned values in the Dim statement
  • However, if values are assigned, you cannot
    declare the Upper Subscript
  • Advice Dont do it

41
General Form Dim Statement for Arrays
Dim ArrayName(UpperSubscript) as Datatype Dim
ArrayName( ) as Datatype InitialValueList
42
Dim Statement for Arrays Examples - Default Values
  • Dim strName(3) as String
  • Results in an array of 4 elements strName(0),
    strName(1),
  • strName(2), strName(3)
  • Dim decBalance(99) as Decimal
  • Results in an array of 100 elements decBalance(
    0), . . . , decBalance(99)

43
Dim Statement for Arrays Examples - Assigned
Values
  • Dim strDept( ) as String "ACT", "MKT", "HR"
  • Dim intActCode( ) as Integer 10, 20, 30, 40

44
What does VB do with the array?
  • When the DIM statement for the array is processed
    VB sets aside room for it in memory.
  • Ex Dim strName(3) as String
  • VB sets aside a memory location for 4 strings

45
Referencing Array Elements
  • Use the Index(s) of the Element

strName(0) "Sam Smith" strName(1) "Jill
Creech" strName(2) "Paul Fry" strName(3)
"Rich Wells"
Sam Smith
Jill Creech
Paul Fry
Rich Wells
46
Working with Arrays
  • Use Loops to reference each element in the array
  • For / Next
  • For Each / Next

47
For Each / Next
  • VB references EACH element of the array
  • VB assigns its value to ElementName
  • The variable used for ElementName must be same
    datatype as the array elements or an Object
    datatype
  • Makes one pass through the loop per element
  • Use Exit For statement within loop to exit early

48
For Each Loop General Form
  • For Each ElementName In ArrayName
  • Statements to execute
  • Next ElementName

49
For Each / Next Examples
' Assumes array strName previously
dimensioned Dim strOneName As String For Each
strOneName In strName Debug.WriteLine(strOneName)
' Write one array element Next strOneName '
Assumes array intTotal previously dimensioned
Dim intOneTotal As Integer For Each intOneTotal
In intTotal intOneTotal0 ' reinitialize the
array Next intOneTotal
50
The following slides are for reference
structures will not be used in programming
testStructures
  • Combine multiple fields of data into a single
    unit
  • Declaration (by default a Structure is Public)
  • Cannot be declared inside a procedure
  • Generally declared in General Declarations
  • Define using Structure, End Structure
  • Once created, declare variable of the Structure
    as if it were another datatype make up a
    meaningful prefix

51
Structure/End Structure General Form
  • PublicPrivate Structure NameOfStructure
  • Dim FirstField As Datatype
  • Dim SecondField As Datatype
  • . . .
  • End Structure

52
Structure Example 1
  • Public Structure Employee
  • Dim intEmpID As Integer
  • Dim strLName As String
  • Dim strFName As String
  • Dim datHireDate As Date
  • End Structure
  • ' Declaring a variable based on the Structure
  • Dim empOffice As Employee

53
Structure Example 2
  • Public Structure Product
  • Dim strDesc As String
  • Dim strProdID As String
  • Dim intQuan As Integer
  • Dim decPrice As Decimal
  • End Structure
  • ' Declaring a variable array based on the
    Structure
  • Dim prdInven(100) As Product

54
Accessing the Elements in a Structure Variable
  • Each field of data in Structure is an Element
  • To access specify Variable.Element
  • Examples

empOffice.intEmpID empOffice.strFName empOffice.s
trLName empOffice.datHireDate
prdInven(intIndex).strDesc prdInven(intIndex).strI
D prdInven(intIndex).intQuan prdInven(intIndex).de
cPrice
55
Including An Array In A Structure
  • Arrays can be included as elements within a
    Structure
  • VB does not, however, allow you to declare the
    number of elements in the array within the
    Structure declaration
  • Use the ReDim statement inside a procedure to
    define the size of the array

56
ReDim Statement
  • Used to redeclare the UpperSubscript/Size of an
    array
  • Can preserve original data in the array
  • General Form (basic)
  • ReDim Preserve ArrayName(UpperSubscript)
  • Examples
  • ReDim Preserve strDept(20)
  • ReDim sdtHousewares.decSale(6)

57
Using Array Elements for Accumulators
intGroupNumCInt(txtGroup.Text)-1
mintTotal array
(0) (1) (2) (3) (4) (5) (6) (7)
58
Table Lookup
  • Problem Often values used to identify a series
    of elements are not
  • Numerically sequential
  • Numerically separated by a constant value
  • Numeric at all, may be strings
  • Solution Create another array to hold the
    identifying values and use a table lookup process
    to find the correct element in the array

59
Table Lookup (cont.)
intIndex2
mgiGroup array
(0) (1) (2) (3) (4) (5) (6) (7)
60
Using List Boxes With Arrays
  • Use List Boxes or Combo Boxes rather than using
    text boxes for the user to enter data used for
    looking up information in the array
  • Use the list's SelectedIndex property as the
    subscript of the corresponding array

61
List Boxes With Arrays (cont.)
SelectedIndex 2 of List Box
mgiGroup array
(0) (1) (2) (3) (4) (5) (6) (7)
62
Multidimensional Arrays
  • Arrays can have more than one dimension
  • Like a table of values
  • You must specify the boundaries for each
    dimension using subscripts
  • Example Two Dimensional Array
  • Dim intScoreBoard (1, 8) as Integer

63
Referencing Elements in Multidimensional Array
intScoreBoard(row,column)
0 1 2 3 4 5 6 7 8
0 1
0,0
0,1
0,2
0,3
0,4
0,5
0,6
0,7
0,8
1,0
1,1
1,2
1,3
1,4
1,5
1,6
1,7
1,8
intScoreBoard(1,0) intScoreBoard(1,1) intScoreBoar
d(1,2) intScoreBoard(1,3) intScoreBoard(1,4) intSc
oreBoard(1,5)
intScoreBoard(0,0) intScoreBoard(0,1) intScoreBoar
d(0,2) intScoreBoard(0,3) intScoreBoard(0,4) intSc
oreBoard(0,5)
64
General Form Dim Statement for Two-Dimensional
Arrays
Dim ArrayName(HighestSubscript, Highest
Subscript) as Datatype Dim ArrayName( , ) as
Datatype ListOfValues
Line continuation not shown on this slide
65
Dim Statement for Two Dimensional-Arrays Examples
  • Dim strName(2, 3) as String
  • Results in an array of 12 elements 3 rows
    0, 1, 2, 3
  • 4 columns 0, 1, 2, 3, 4
  • Dim strName( , ) as String "Jim", "Mary",
    "Sam", "Sean", "Tom", "Sue", "Fred", "Paul",
    "Tim", "Al", "Bob", "Pete", "Joy", "Wes",
    "Kim", "Beth"
  • Results in same array as above with default
    values

Line continuation not shown on this slide
66
Working WithTwo-Dimensional Arrays
  • Initializing/Reinitializing
  • Use Nested For/Next Loops
  • Use For Each/Next Loop
  • Printing
  • Use For Each/Next Loop
  • Summing
  • Include a total field for each row and each
    column
  • Use For/Next Loop to calculate sums

67
Initializing For/Next Example
Dim intRow As Integer Dim intColumn As
Integer For intRow 0 to 2 For intColumn 0 to
3 strName(intRow, intColumn) " " Next
intColumn Next intRow
68
Initializing For Each/Next Example
Dim strElement As String For Each strElement In
strName strElement " " Next strElement
69
Summing Example
decAmount(3,5)
decRowTotal(3)
0 1 2 3 4 5
0 1 2 3
0 1 2 3
ROWTOTALS
COLUMNTOTALS
decColTotal(5)
0 1 2 3 4 5
70
Summing Code Example
'Crossfoot Total a 2D table Dim decAmount(3,5) As
Decimal Dim decRowTotal(3) As Decimal Dim
decColTotal(5) As Decimal Dim intRowIndex As
Integer Dim intColIndex As Integer For
intRowIndex 0 to 3 For intColIndex 0 to
5 decRowTotal(intRowIndex)
decAmount(intRowIndex, intColIndex) decColTotal(
intColIndex) decAmount(intRowIndex,
intColIndex) Next intColIndex Next intRowIndex
71
Lookup Two-Dimensional Tables
  • Use same techniques as for single dimension
    arrays
  • Direct Reference (if meaningful row and column
    subscripts are available)
  • Table Lookup
  • Many 2D tables used for lookup will require
    additional one-dimensional arrays or list boxes
    to aid in the lookup process

72
Lookup Example Using List Box
Weight Subscript of Array uses lstWeight.SelectedI
ndex
Zone Subscript of Array uses lstZone.SelectedIndex
73
Debugging Array Programs
  • View the array elements in Break Time in the
    Autos Window or the Locals Window

74
End of fundamental programming constructs
  • You must know all about
  • Variables, Constants
  • If..Then..Else, Case
  • Loops
  • Lists
  • Arrays
  • Full Stop (.) method of accessing Properties
    Methods
  • Property and method names of common controls
  • Questions?
Write a Comment
User Comments (0)
About PowerShow.com