0% found this document useful (0 votes)
8 views32 pages

Arrays: Programming in

Chapter 8 discusses arrays in Visual Basic.NET, explaining their structure, declaration, and usage. It covers the use of Case structures for decision-making, sharing event procedures, and the importance of the CType function for type conversion. Additionally, it details how to work with multidimensional arrays and structures, including initialization, referencing elements, and summing values.

Uploaded by

Russel Gurat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views32 pages

Arrays: Programming in

Chapter 8 discusses arrays in Visual Basic.NET, explaining their structure, declaration, and usage. It covers the use of Case structures for decision-making, sharing event procedures, and the importance of the CType function for type conversion. Additionally, it details how to work with multidimensional arrays and structures, including initialization, referencing elements, and summing values.

Uploaded by

Russel Gurat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 32

Chapter 8

Arrays

Programming In
Visual Basic.NET
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

8- 2 © 2001 by The McGraw-Hill Companies, Inc. All rights reserved.


Select Case General Form
(also notice indenting)
Select Case
expression
If expression=value in
Case ConstantList constant list
[ code to run]
[Case ConstantList If expression=value in
[ code to run]] constant list
[Case Else ]
[code to run]] If expression< >values in any
End Select of the preceding constant lists

** Case Else is an optional clause


8- 3 © 2001 by The McGraw-Hill Companies, Inc. All rights reserved.
Select Case - Numeric Value
Example 1
Private Function CalculateGrade(ByVal intScore As Integer) as
String
Select Case intScore
Case Is >= 90
Return "A"
Case 80 to 89
Return "B"
Case 70 to 79
Return "C"
Case 60 to 69
Return "D“
Case Else 'accommodate all other values
Return "F"
End Select
End Function
8- 4 © 2001 by The McGraw-Hill Companies, Inc. All rights reserved.
Select Case - Numeric Value
Example 2

Select Case intListIndex


Case 0
HandleItemZero( )
Case 1, 2, 3
HandleItems( )
Case Else
HandleNoSelection( )
End Select

8- 5 © 2001 by The McGraw-Hill Companies, Inc. All rights reserved.


Select Case - String Value Example
Select Case mstrSelectedButton
Case "radQuarter“: intRow
=0
Case "radHalf“: intRow = 1
Case "radFull“ : intRow = 2
Case Else ‘ use default
intRow = 0
End Select

8- 6 © 2001 by The McGraw-Hill Companies, Inc. All rights reserved.


Sharing an Event Procedure
• If the code for multiple controls is very similar,,
the controls can share an event procedure
• Use the Handles Clause to add multiple controls
to a handler
Private Sub radBlack_CheckChanged(ByVal sender as System.Object, _
byVal e as System.Event.Args) Handles radBlack.CheckChanged, _
radBlue.CheckChanged, radRed.CheckChanged, _
radWhite.CheckChanged, radYellow.CheckChanged

[block of code]
End Sub

8- 7 © 2001 by The McGraw-Hill Companies, Inc. All rights reserved.


sender Argument
• sender argument is the key to using the shared event
• sender is a System.Object type with Name property
• Possible Problem
– if Option Strict is turned on, reference to sender.Name will
cause a compile error for Late Binding (i.e. type cannot be
determined until run time rather than at compile time)
• Solution
– use CType function to convert sender to a specific object
type, thus providing Early Binding

8- 8 © 2001 by The McGraw-Hill Companies, Inc. All rights reserved.


CType Function
• Converts object from one type to another
• General Form
CType (ValueToConvert, NewType)
• Example

Dim radSelected As RadioButton


radSelected = CType(sender,
RadioButton)
Select Case radSelected .Name
Case "radBlue"
. . .
8- 9 © 2001 by The McGraw-Hill Companies, Inc. All rights reserved.
Sharing Event Example
' Declare a module level variable for storing color
Dim mColorNew as Color ‘declare it module level
...
Private Sub radBlack_CheckChanged(ByVal sender as System.Object, _
byVal e as System.Event.Args) Handles radBlack.CheckChanged, _
radBlue.CheckChanged, radRed.CheckChanged, _
radWhite.CheckChanged, radYellow.CheckChanged

Dim radSelected as RadioButton

radSelected = CType (sender, RadioButton) ‘early binding


Select Case radSelected.Name
Case "radBlack“ : mColorNew = Color.Black
Case "radBlue“ : mColorNew = Color.Blue
Case "radRed“ : mColorNew = Color.Red
Case "radWhite“ : mColorNew = Color.White
Case "radYellow“ : mColorNew = Color.Yellow
End Select
End Sub
8- 10 © 2001 by The McGraw-Hill Companies, Inc. All rights reserved.
Arrays
• Array is a collection of strName
values referenced in memory
by the same name (0) Janet Baker
• Similar to list of items for (1) George Lee
(2) Sue Li
list boxes and combo boxes
(3) Samuel
- without the box
(4) Hoosier
• Use an array to keep a series (5) Sandra Weeks
of variable for later (6) William Macy
processing such as (7) Andy Harrison
– Reordering (8) Ken Ford
– Calculating (9) Denny Franks
– Printing Shawn James
8- 11 © 2001 by The McGraw-Hill Companies, Inc. All rights reserved.
Array Terms
strName
• Element
– Individual item in the array (0) Janet Baker
(1) George Lee
• Index (or subscript)
(2) Sue Li
– Zero based number used to (3) Samuel
reference the specific (4) Hoosier
elements in the array (5) Sandra Weeks
– Must be an integer (6) William Macy
• Boundaries (7) Andy Harrison
(8) Ken Ford
– Lower Subscript, 0 by default
(9) Denny Franks
– Upper Subscript Shawn James

8- 12 © 2001 by The McGraw-Hill Companies, Inc. All rights reserved.


Two Ways to Declare Arrays
• Using upper bound versus assigned values
Dim ArrayName (UpperSubscript ) as Datatype
‘ In this case each element of the array will be assigned a
default
‘value: numeric  0, string  “” (no characters)
Dim ArrayName ( ) as Datatype = {InitialValueList}
‘No upper Subscript is allowed
• Examples
Dim strName (3) as String ‘an array of 4
elements:
Dim decBalance(99) as Decimal ‘an array of 100
elements:

Dim strDept ( ) as String = {"ACT", "MKT", "HR", "MIS"}


8-Dim
13 intActCode ( ) as©Integer = {10, 20, 30, 40}
2001 by The McGraw-Hill Companies, Inc. All rights reserved.
Referencing Array Elements

• Use the Index(s) of the Element

strName strName(0) : "Sam Smith"


(0) Sam Smith strName(1) : "Jill Creech"
(1) Jill Creech strName(2) : "Paul Fry"
(2) Paul Fry
strName(3) : "Rich Wells"
(3) Rich Wells

8- 14 © 2001 by The McGraw-Hill Companies, Inc. All rights reserved.


For Each / Next Loop
 General Form
For Each ElementName In ArrayName
Statements to execute
Next [ElementName]

 Example
' Assumes array intTotal previously dimensioned
Dim intOneTotal As Integer ‘must be the same type as
intTotal
For Each intOneTotal In intTotal ‘references EACH
element
intOneTotal=0 ' reinitialize element of the
array
8- 15
Next intOneTotal © 2001 by The McGraw-Hill Companies, Inc. All rights reserved.
Structures
• 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

8- 16 © 2001 by The McGraw-Hill Companies, Inc. All rights reserved.


Structure Declaration
 General Form
[Public|Private] Structure NameOfStructure
Dim FirstField As Datatype
Dim SecondField As Datatype
...
End Structure
Dim manyStructuredVar As NameOfStructure

Example
Structure CoffeeSale
Dim strType As String
Dim strQuantity As String
Dim decPrice As Decimal
End Structure
Dim mcslTransaction(20) As CoffeeSale
8- 17 © 2001 by The McGraw-Hill Companies, Inc. All rights reserved.
Accessing the Elements in a
Structure Variable
• Each field of data in Structure is an Element
• To access specify Variable.Element
• Examples
empOffice.intEmpID prdInven(intIndex).strDesc
empOffice.strFName prdInven(intIndex).strID
empOffice.strLName prdInven(intIndex).intQuan
empOffice.datHireDate prdInven(intIndex).decPric
e

8- 18 © 2001 by The McGraw-Hill Companies, Inc. All rights reserved.


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

8- 19 © 2001 by The McGraw-Hill Companies, Inc. All rights reserved.


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)

8- 20 © 2001 by The McGraw-Hill Companies, Inc. All rights reserved.


Table Lookup Using Structures
Structure Student
strStudentID As String
strUserName As String
End Structure
mstuStudents(99) As Student
.......
Dim intIndex As Integer
Dim blnFound As Boolean
blnFound = False
intIndex = 0
Do Until blnFound Or intIndex > 99
If mstuStudents(intIndex).strStudentID = txtID.Text Then
blnFound = True
lblEmail.Text = mstuStudents(intIndex).strUserName _
& "@clarkson.edu“
End If
intIndex = intIndex + 1
Loop
If blnFound = False Then MsgBox "There is no such student in the
list."
8- 21 © 2001 by The McGraw-Hill Companies, Inc. All rights reserved.
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
0 1 2 3 4 5 6 7 8
0
1

8- 22 © 2001 by The McGraw-Hill Companies, Inc. All rights reserved.


Referencing Elements in
Multidimensional Array
intScoreBoard(row,column)
0 1 2 3 4 5 6 7 8
0 0,0 0,1 0,2 0,3 0,4 0,5 0,6 0,7 0,8
1 1,0 1,1 1,2 1,3 1,4 1,5 1,6 1,7 1,8

intScoreBoard(0,0) intScoreBoard(1,0)
intScoreBoard(0,1) intScoreBoard(1,1)
intScoreBoard(0,2) intScoreBoard(1,2)
intScoreBoard(0,3) intScoreBoard(1,3)
intScoreBoard(0,4) intScoreBoard(1,4)
intScoreBoard(0,5) intScoreBoard(1,5)

8- 23 © 2001 by The McGraw-Hill Companies, Inc. All rights reserved.


Declaring Two-Dimensional Arrays
 General Form
Dim ArrayName(HighestSubscript, Highest Subscript) as
Datatype

Dim ArrayName( , ) as Datatype = {ListOfValues}


 Example
Dim strName(2, 3) As String
‘ Results in an array of 12 elements:
‘3 rows: 0, 1, 2 and 4 columns: 0, 1, 2, 3

Dim strName( , ) As String = {{"Jim", "Mary", "Sam",


"Sean"}, _
{"Tom", "Sue", "Fred",
"Paul"}, _
{"Tim", "Al", "Bob", "Pete"}}
‘ Also results in an array of 12 elements:
8- 24 © 2001 by The McGraw-Hill Companies, Inc. All rights reserved.
‘ 3 rows: 0, 1, 2 and 4 columns: 0, 1, 2, 3
Using Two-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

8- 25 © 2001 by The McGraw-Hill Companies, Inc. All rights reserved.


Initializing / Reinitializing
 Using For/Next loops
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

Using For Each/Next loops


Dim strElement As String
For Each strElement In strName
strElement = " "
Next strElement
8- 26 © 2001 by The McGraw-Hill Companies, Inc. All rights reserved.
Printing Example
'Print one name per line
For Each strElement In strName
'Set up a line
e.Graphics.DrawString(strElement, fntPrintFont, _
Brushes.Black, sngPrintX, sngPrintY)
'Increment the Y position for the next line
sngPrintY += sngLineHeight
Next strElement

8- 27 © 2001 by The McGraw-Hill Companies, Inc. All rights reserved.


Summing Example
decAmount(3,5)
0 1 2 3 4 5 decRowTotal(3)
0 0
ROW 1
1
TOTALS
2 2
3 3
COLUMN
TOTALS

decColTotal(5)
0 1 2 3 4 5
8- 28 © 2001 by The McGraw-Hill Companies, Inc. All rights reserved.
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
8- 29 © 2001 by The McGraw-Hill Companies, Inc. All rights reserved.
Lookup Two-Dimensional
Tables
 Lookup for an intersection cell
(VBMailOrder example)

 Lookup for a corresponding value


(VBAutoCenter example)

8- 30 © 2001 by The McGraw-Hill Companies, Inc. All rights reserved.


Lookup For an Intersection Cell

Dim mdecCharge(,) As Decimal = {{1D, 1.5D, 1.65D, 1.85D}, _


'other elements specified}
.......
Dim intCol, intRow As Integer
Dim decCharge As Decimal
'Look up the price.
intRow = lstWeight.SelectedIndex 'determine the row
intCol = lstZone.SelectedIndex 'determine the column
decCharge = CDec(mdecCharge(intRow, intCol)) 'find
the Charge lblCharge.Text = FormatCurrency(decRate)
'display formatted
8- 31 © 2001 by The McGraw-Hill Companies, Inc. All rights reserved.
Lookup For a Corresponding Value

'Determine the brand row. intRow for VB Brand is 0.


Select Case mstrSelectedRad
Case "radA" : intCol = 1
Case "radC" : intCol = 2
Case "radX" : intCol = 3
End Select
'Determine the entered number's row.
Dim blnFound As Boolean = False
For intRow = 0 To 8
If strParts(intRow, intCol) = txtTheirNumber.Text
Then
lblVBEquivalent.Text = strParts(intRow, 0)
blnFound = True
Exit For
8- 32 End
© 2001 byIfThe McGraw-Hill Companies, Inc. All rights reserved.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy