View
49
Download
0
Category
Tags:
Preview:
DESCRIPTION
CVEV 118/698 Visual Basic. Lecture 2. Prof. Mounir Mabsout Elsa Sulukdjian Walid El Asmar. Control Flow Statements. An important feature in programming languages is the ability to examine external conditions and act accordingly. VB provides three control flow (or decision) statements: - PowerPoint PPT Presentation
Citation preview
CVEV 118/698CVEV 118/698 Visual Basic Visual Basic
Lecture 2Lecture 2
Prof. Mounir MabsoutProf. Mounir MabsoutElsa SulukdjianElsa SulukdjianWalid El AsmarWalid El Asmar
Control Flow StatementsControl Flow Statements
An important feature in An important feature in programming languages is the programming languages is the ability to examine external ability to examine external conditions and act accordingly.conditions and act accordingly.
VB provides three control flow (or VB provides three control flow (or decision) statements:decision) statements:– If … Then … End IfIf … Then … End If– If … Then … Else … End If (Elseif)If … Then … Else … End If (Elseif)– Select CaseSelect Case
If/Then StatementsIf/Then Statements Example 1:Example 1:
If If intAnswer = 1 intAnswer = 1 ThenThenstrMood = “happy”strMood = “happy”
End IfEnd If
Example 2:Example 2: If If intAnswer = 1 intAnswer = 1
ThenThenstrMood = “happy”strMood = “happy”
ElseElsestrMood = “sad”strMood = “sad”
End IfEnd If
Example 3:Example 3:IfIf intAnswer = 1 intAnswer = 1 ThenThen
strMood = “happy”strMood = “happy”Elseif Elseif intAnswer = 2 intAnswer = 2
ThenThenstrMood = “sad”strMood = “sad”
ElseElsestrMood = “don’t strMood = “don’t care”care”
End IfEnd If
Select Case StatementSelect Case Statement Efficient method for multi-conditional cases.Efficient method for multi-conditional cases.
Select Case expressionCase Value_1
Statement block_1Case Value_2
Statement block_2…
Case Value_nStatement block_n
Case ElseStatement block
End Select
Select Case WeekDay(intDate) Case 1
strDayName = “Monday”strMessage = “Have a
nice week” Case 6
strDayName = “Saturday”strMessage = “Have a
nice weekend” Case 7
strDayName = “Sunday”strMessage = “Working
on Sunday!!??” Case Else
strMessage = “Welcome back”End Select
Select Case (cont’d)Select Case (cont’d) The The Select CaseSelect Case structure compares the structure compares the
results of one expression to several values, and results of one expression to several values, and if it matches one of them, the corresponding if it matches one of them, the corresponding block of statement is executed.block of statement is executed.
If more than one Case value matches the If more than one Case value matches the expression, only the statement block associated expression, only the statement block associated with the first matching Case executes.with the first matching Case executes.
Disadvantage: The Select Case evaluates the Disadvantage: The Select Case evaluates the expression before entering the Case expression before entering the Case statements, while the If/Then/Else can evaluate statements, while the If/Then/Else can evaluate a different expression for each ElseIf statement.a different expression for each ElseIf statement.
Select Case (cont’d)Select Case (cont’d) Example 2Example 2
Select Case WeekDay(intDate)Select Case WeekDay(intDate) Case 1, 2, 3, 4, 5Case 1, 2, 3, 4, 5
strDayType = “Workday”strDayType = “Workday”strMessage = “Enjoy Work”strMessage = “Enjoy Work”
Case 6, 7Case 6, 7strDayType = “Holiday”strDayType = “Holiday”strMessage = “Enjoy your weekend”strMessage = “Enjoy your weekend”
Case ElseCase ElsestrDayType = “VBday”strDayType = “VBday”strMessage = “Goto your assignment!”strMessage = “Goto your assignment!”
End SelectEnd Select
Loop StatementsLoop Statements
Loop Statements Loop Statements allow to execute allow to execute code repetitively.code repetitively.
VB provides three loop statements:VB provides three loop statements:– Do … LoopDo … Loop– For … NextFor … Next– While … WendWhile … Wend
Do … LoopDo … Loop Syntax 1:Syntax 1: Do WhileDo While condition condition
statement blockstatement blockLoopLoop
VB evaluates the VB evaluates the conditioncondition, if it is False the , if it is False the block is never executed. If it is True, VB executes block is never executed. If it is True, VB executes the statement block, re-evaluates the the statement block, re-evaluates the conditioncondition, , and repeats the statement block if it is True.and repeats the statement block if it is True.
Example 1:Example 1: Do WhileDo While dblGrade <= 80 dblGrade <= 80dblGrade = dblGrade + 1dblGrade = dblGrade + 1MsgBox “Work Harder!”MsgBox “Work Harder!”
LoopLoop
Do … Loop (cont’d)Do … Loop (cont’d) Syntax 2:Syntax 2: DoDo
statement blockstatement blockLoop While Loop While conditioncondition
The main difference with syntax 1 is that the The main difference with syntax 1 is that the statement block is executed the first time statement block is executed the first time independently of the condition. The evaluation independently of the condition. The evaluation starts before the second loop.starts before the second loop.
Example 2:Example 2: Do Do dblGrade = dblGrade = dblGrade + 1dblGrade + 1
MsgBox “Work Harder!”MsgBox “Work Harder!”Loop While Loop While dblGrade <= 80dblGrade <= 80
For … NextFor … Next
The loop executes depending on a The loop executes depending on a preset number of times not on a preset number of times not on a conditional statement.conditional statement.
It uses a variable (counter) that It uses a variable (counter) that increases or decreases in value each increases or decreases in value each time the statement is executed.time the statement is executed.
SyntaxSyntax::ForFor counter = start counter = start ToTo end [ end [StepStep
increment]increment]statementsstatements
NextNext [counter] [counter]
For … Next (cont’d)For … Next (cont’d)
Example 1:Example 1:For intNum = 1 to 10For intNum = 1 to 10
intSquareNum(intNum) = intNum * intNumintSquareNum(intNum) = intNum * intNumNext intNum Next intNum
Unless specified, the incremental step Unless specified, the incremental step of the counter (I.e. intNum) is 1 by of the counter (I.e. intNum) is 1 by default.default.
Example 2:Example 2:For intNum = 10 to 1 Step -2For intNum = 10 to 1 Step -2
intSquareNum(intNum) = intNum * intNum intSquareNum(intNum) = intNum * intNum Next intNumNext intNum
While … WendWhile … Wend
While…Wend executes a block of While…Wend executes a block of statements while a condition is true.statements while a condition is true.
Syntax:Syntax:WhileWhile condition condition
statement blockstatement block
WendWend Why all this trouble?Why all this trouble?
Just use the Do While Loop Just use the Do While Loop
Functions & SubroutinesFunctions & Subroutines
VB code is not a monolithic listing. An VB code is not a monolithic listing. An application in VB is made up of small self application in VB is made up of small self contained segments that are “event contained segments that are “event handler”.handler”.
Difference between a function & a Difference between a function & a subroutine:subroutine:– A Function executes a series of commands A Function executes a series of commands
and returns a value.and returns a value. – A Subroutine can be considered a special A Subroutine can be considered a special
function since it does not return anything.function since it does not return anything.
SubroutinesSubroutines
A subroutine is a block of statements A subroutine is a block of statements that carry out a well-defined task.that carry out a well-defined task.Sub MyFirstSub ()Sub MyFirstSub ()
…………
…………
End SubEnd Sub All the event procedures in VB are All the event procedures in VB are
coded as subroutines e.g.: the coded as subroutines e.g.: the “click” event of a button.“click” event of a button.
FunctionsFunctions
A function returns a result, A function returns a result, accordingly it must have a type:accordingly it must have a type:Function MyFirstFunction () As DoubleFunction MyFirstFunction () As Double
…………
…………
End FunctionEnd Function
ArgumentsArguments Arguments are values passed to a Arguments are values passed to a
procedure (a function or subroutine) procedure (a function or subroutine) and on which the procedure acts.and on which the procedure acts.
Example:Example:Function dblCircleArea (Function dblCircleArea (r As Doubler As Double) As Double) As Double
dblCircleArea = pi * r * rdblCircleArea = pi * r * r
End FunctionEnd Function
To call the above function:To call the above function:
dblCArea1 = dblCircleArea (dblRadius)dblCArea1 = dblCircleArea (dblRadius)
(where dblCArea1 & dblRadius are previously (where dblCArea1 & dblRadius are previously defined variables of type double)defined variables of type double)
Arguments (cont’d)Arguments (cont’d) The number of arguments passed must The number of arguments passed must
be the same as the number of arguments be the same as the number of arguments defined in the function or subroutine.defined in the function or subroutine.
Example:Example:Function dblRectArea (Function dblRectArea (a, b As Doublea, b As Double) As Double) As Double
dblRectArea = a * bdblRectArea = a * b
End FunctionEnd Function
‘‘Error will be generated in the following code:Error will be generated in the following code:
dblAreaWrong = dblRectArea(dblLength)dblAreaWrong = dblRectArea(dblLength)
‘‘The right piece of code is:The right piece of code is:
dblAreaRight = dblRectArea(dblLength,dblWidth)dblAreaRight = dblRectArea(dblLength,dblWidth)
Optional ArgumentsOptional Arguments You may need a function to handle in some cases You may need a function to handle in some cases
one argument; in other cases two or more. one argument; in other cases two or more. Then you need to use the “Optional argument”:Then you need to use the “Optional argument”:
Function dblRectArea (a As Double,Function dblRectArea (a As Double, Optional b As DoubleOptional b As Double) As ) As DoubleDouble
dblRectArea = a * adblRectArea = a * aIf IsMissing(b) Then Exit FunctionIf IsMissing(b) Then Exit FunctiondblRectAtea = a * bdblRectAtea = a * b
End FunctionEnd Function
Both calls for the above function are valid:Both calls for the above function are valid:RArea1 = dblRectArea(dblLength)RArea1 = dblRectArea(dblLength)RArea2 = dblRectArea(dblLength,dblWidth)RArea2 = dblRectArea(dblLength,dblWidth)
FormsForms A A form is the “container” which includes all the form is the “container” which includes all the
“controls” that make up the user interface.“controls” that make up the user interface. Forms have a built-in functionality that is always Forms have a built-in functionality that is always
available without any coding from you (title bar, available without any coding from you (title bar, resize, etc.).resize, etc.).
• Properties of a form exist for you to customize its Properties of a form exist for you to customize its appearance. Some of these properties are:appearance. Some of these properties are:– MinButton, MaxButtonMinButton, MaxButton– BorderStyleBorderStyle– ControlMenuControlMenu
Control Menu
Title Bar Minimize Maximize
Close
Forms (cont’d)Forms (cont’d)
Basic ControlsBasic Controls
Controls are Controls are another key factors in the “event-driven” programming.
VB has a multitude of controls, and many third party companies are developing more.
You can create your own control.
Frames and Option BoxesFrames and Option Boxes
Rectangular entity inside a form that Rectangular entity inside a form that groups one or more controls.groups one or more controls.
Frames are used for esthetics Frames are used for esthetics reasons and/or for proper reasons and/or for proper functioning of option boxes: inside functioning of option boxes: inside each frame, only one option box can each frame, only one option box can be tickedbe ticked
Frames and Option Boxes: Example
TextBox PropertiesTextBox Properties Multiline: set to true if you want to display correctly
multiple lines. PasswordChar: set to a character that gets displayed
to hide the real characters. ToolTipText: Yellowish text box that explains about a
control. ScrollBars: Controls the attachment of scroll bars, if
the text exceeds the control dimensions. MaxLength: Maximum number of characters
contained. TabStop: Controls the access to the control with the
tab key. Enabled: Controls the access to the control
What’s NextWhat’s Next
Form manipulationForm manipulation Menu designMenu design Other controlsOther controls
Recommended