‘tirgul’ # 3 enterprise development using visual basic 6.0 autumn 2002 tirgul #3
TRANSCRIPT
‘Tirgul’ # 3
Enterprise Development Using Visual Basic 6.0
Autumn 2002
Tirgul #3
‘Tirgul’ # 3
Short Quiz
• Write a simple Function that receives a String and returns its length
• Write a Simple Function that receive an Integer, if it is negative, returns a String with error message, otherwise returns the Integer as a String
‘Tirgul’ # 3
Objectives• Parameters passing• Getting Deeper
– If – Then – Else– Case– Loops
• Arrays– Dimension arrays correctly– Recognize the default values of array elements– Access array items by subscript or all elements in a loop– Use parallel arrays for storage of related lists of items– Use list boxes for displaying choices– Use 2-D arrays
‘Tirgul’ # 3
Review: important concepts• Remember to plan your programs
(algorithm) before starting to write the code! (80:20)
• Use procedures and functions
– parameters must be carefully set
– Use ByRef and ByVal
• Fundamental Structures:
– Sequence, Selection, and Iteration
‘Tirgul’ # 3
Parameter Passing
• By default, variables are passed ByRef
– called procedure uses same memory location for the variable
– assigns a new name for that location, uses that name within the procedure
– contents of this location may be changed
Sub Add_And_Change (ByRef x as Single, ByRef y as Single)x = x + y
End Sub
‘Tirgul’ # 3
Parameter passing
• Parameters can also be passed ByVal– called procedure sets up new memory
locations– value of parameter is copied into the new
locations– changes do not affect original variable
Sub Add_And_Print (ByVal x as Single, ByVal y as Single)x = x + ypicOut.print x
End Sub
Example
What will be printed out?
What if we called
Sample2 (b, a) ?
Sub Sample1 (ByRef x as Single, ByRef y as Single)
x = x - ypicOut x, y
End Sub
Sub Sample2 (ByVal x as Single, ByVal y as Single)
x = x - ypicOut x, y
End Sub
Sub cmdComputeDim a, b as Singlea = 2b = 3Sample2 (a, b)picOut1.Print a, bSample1 (a, b)picOut.Print a, b
End Sub
‘Tirgul’ # 3
Nested IF statements
If condition1 Then
If condition2 Then
statement1
End If
Else
statement2
End if
‘Tirgul’ # 3
ExampleIf Grade >= 90 Then
txtLetterGrade.Text = “A”
Else
If Grade >=80 Then
txtLetterGrade.Text = “B”
Else
txtLetterGrade.Text = “C”
End If
End If
‘Tirgul’ # 3
ExampleIf Income >= 40000 Then
If Status = “Single” Then
TaxRate = 0.33
ElseIf Status = “Married” Then
TaxRate = 0.25
End If
Else
sTaxRate = .15
End If
Less end if’s
‘Tirgul’ # 3
If statement summary• VB is sensitive at design-time and run-
time
• Indentation!
• Use if… Then
• Use end if
• Use elseif
Sub Sample_if () If a = b then … End ifEnd Sub
Sub Sample_if2 () If a = b then … elseif … End ifEnd Sub
Sub Sample_if2 () If a = b then … else if a > b then … end if End ifEnd Sub
‘Tirgul’ # 3
Select Case Structure• Multiple IF statements can be replaced by more
readable Select CASE statements
Select Case selector Case valueList1
action1 Case valueList2
action 2 … Case Else
if no other matchEnd Select
valueList options:Case 1
Case 2 to 5
Case 6, 9
Case “text”
Case Is >= 10
‘Tirgul’ # 3
Example
Select case AccessCode
case is < 1000
message = “Access Denied”
case 1465 To 1689
message = “Technical Personal”
case 999898 , 10000006 To 10000008
message = “Scientific Personal“
case Else
message = “Access Denied”
End Select
‘Tirgul’ # 3
Case statement summary
• Use String/Integer type
• When using String pay attention to content!
• Don’t forget default
‘Tirgul’ # 3
Do / Loops
Format 2:
Do
loop body
Loop {While | Until} Condition
Format 1:
Do {While | Until} Conditionloop body
Loop
•Loop body executes while the condition is true or until the condition is true
•The first form uses a pretest, the second uses a posttest.
•With a pretest, loop may not execute at all.
•With a posttest, loop always executes at least once.
‘Tirgul’ # 3
Do While Example
Do While sTotal < 25
sNum = Val(Inputbox(“Enter a number”))
If sNum > 0 then
sTotal = sTotal + sqr(sNum)
End If
Loop
‘Tirgul’ # 3
Choosing Loop Type
• For..Next loop should be used when you know the number of loops
• Do ..While is used when you do not know in advance the number of iteration.
– Examples• You want to get user input until she hits
the escape button• You want your server to keep listening
for request until it receives a shut down message.
‘Tirgul’ # 3
Loops summary
• For – next
• While – wend
• Do – while
• Common mistakes
– Stop condition
– Increment
• Exit loop
Do For I = 1 To 1000 MyNum = Int(Rnd * 100) Select Case MyNum Case 7: Exit For Case 29: Exit Do Case 54: Exit Sub End Select Next I Loop
While true … index = index +1Wend
Danger
‘Tirgul’ # 3
Arrays
• Array – Set of elements of the same type indexed in a data structure
• Each array object is called an element
• Each element is identified with an Index
‘Tirgul’ # 3
Why use arrays?• Often, all data must be read in and stored for
future use.• Not always possible to get each value and process
it, it is better to get all data, store it in an array and process it
• Use of data structures is preferred and unavoidable.
‘Tirgul’ # 3
Declaration• Array name - identifier
• Array type – type of elements in the array
• Array range – how many elements
class(1) class(30)
Dim class(1 to 10) as students
‘Tirgul’ # 3
Subscripts
• Recall – Array starts at 1 BUT:
• Array of size 25
• subscripts may be constants, variables, or numeric expressions
• Use Constants!!!
Dim GradeArr(MAX_STUDENTS) as Single
Dim GradeArr(0 to 29) as Single
‘Tirgul’ # 3
Array Value setDim GradeArr(1 to MAX_STUDENTS) as Single
GradeArr(1) = 95
for index = 2 to 10
GradeArr(index) = 100
next index
GradeArr(11) = (sGrade(1) + sGrade(2) )/2
GradeArr(30) = ?
‘Tirgul’ # 3 24
Array bounds• Ubound, Lbound will return the array
declared size (NOT elements)
• To prevent errors, check Ubound for highest index
• Common use to iterate the array:
for index = Lbound(GradeArr) to Ubound(GradeArr)
…
next index
‘Tirgul’ # 3 25
Declaring Dynamic Array• An Array declaration at the module level – No
memory location yet:
• Memory allocation at sub/function level:
Dim DBConnections() as Connection
Public DBRecordSet() as RecordSet
Sub openConnection ()
. . .
ReDim DBConnections(1 To MAX_CONNECTIONS)
End sub
‘Tirgul’ # 3 26
Redim• Resizing an existing array• Procedure level allocation• Deallocate memory (free memory)
• Array values are lost at Redim!• Use preserve to keep old values
ReDim preserve newArray(MAX_ARRAY_SIZE + 1)
Redim array(0)
‘Tirgul’ # 3
For Each…Next Statement• Use For Each…Next Iteration to iterate al
array elements
• Use variant type variable if you don’t know element type.
Dim day as Variant
For each day in week
print day
Next day
‘Tirgul’ # 3
Split - Join• Split – Namely split a String to the array
• Join – Namely create a String from array
dim wordsArr()as String
dim Sentence as string
Sentence = “good morning”
wordsArr = Split(Sentence,“ “ )
Sentence = join(wordsArr,“ “)
1
2
Good
Morning
wordsArr
Sentence
“good morning”
Delimiter
‘Tirgul’ # 3
Two-Dimensional Arrays
• Think of a table structure
• use two indexes
– row index
– column index
• all elements must be of the same type
‘Tirgul’ # 3
Examples
• Dim iArray (1 to 2, 1 to 5) as Integer
• array of 2 rows and 5 columns
Col
Row
‘Tirgul’ # 3
Accessing Array Elements
• iArray (1, 2) = 10
• iArray (2, 5) = iArray(1, 4) + iArray(1, 5)
• I = 7 : J = 5
sGrades (I, J) = 93
• x = 1 : y = 2
iArray (1, x + y) = 15
‘Tirgul’ # 3
Practical - Combo Boxes• Combo box represent a list of items to select
from.• Items can be specified during Design/Run
time• Uses:
– Inset Item– Delete Item– Get selected Item
‘Tirgul’ # 3
Code sample for Combo Box
• ListIndex represents the selected Index• Text represents the item String value
• Remove selected item
• Add items to list
cmbDays.RemoveItem cmbDays.ListIndex
cmbDays.AddItem “Sunday”
Debug.print cmbDays.text
‘Tirgul’ # 3
Using Combo Boxes As an Array
• Combo box is an array controlled by VB
• Count – combobox.ListCount
• Add/Remove operations
• Lists start at 0, array at 1
Fill
Clear
Count
‘Tirgul’ # 3
Controls array• In a from, you can group elements
– Tab, Option button…
• Useful when having lots of controls
• Notation:
• Design time
– Copy/Paste in the form
– setting index
Option(0), Option(1)