Lesson 7 - If / If Then Else / Nested If Statements Control Structure
2:37 AM
| Posted by
Unknown
|
Control Statements are used to control the flow of program's execution. Visual Basic supports control structures such as if... Then, if...Then ...Else, Select...Case, and Loop structures such as Do While...Loop, While...Wend, For...Next etc method.
If...Then selection structure
The If...Then selection structure performs an indicated action only when the condition is True; otherwise the action is skipped.
Syntax of the If...Then selection
If <condition> Then
statement
End If
e.g.: If average>75 Then
txtGrade.Text = "A"
End If
Using If.....Then.....Else Statements with Operators
To effectively control the VB program flow, we shall use If...Then...Else statement together with the conditional operators and logical operators.
The general format for the if...then...else statement is
If conditions Then
VB expressions
Else
VB expressions
End If
* any If..Then..Else statement must end with End If. Sometime it is not necessary to use Else.
Example:
Private Sub OK_Click()
firstnum=Val(usernum1.Text)
secondnum=Val(usernum2.Text)
If total=firstnum+secondnum And Val(sum.Text)<>0 Then
correct.Visible = True
wrong.Visible = False
Else
correct.Visible = False
wrong.Visible = True
End If
End Sub
Nested If...Then...Else selection structure
Nested If...Then...Else selection structures test for multiple cases by placing If...Then...Else selection structures inside If...Then...Else structures.
Syntax of the Nested If...Then...Else selection structure
You can use Nested If either of the methods as shown above
Method 1
If < condition 1 > Then
statements
ElseIf < condition 2 > Then
statements
ElseIf < condition 3 > Then
statements
Else
Statements
End If
Method 2
If < condition 1 > Then
statements
Else
If < condition 2 > Then
statements
Else
If < condition 3 > Then
statements
Else
Statements
End If
End If
EndIf
e.g.: Assume you have to find the grade using nested if and display in a text box
If average > 75 Then
txtGrade.Text = "A"
ElseIf average > 65 Then
txtGrade.Text = "B"
ElseIf average > 55 Then
txtGrade.text = "C"
ElseIf average > 45 Then
txtGrade.Text = "S"
Else
txtGrade.Text = "F"
End If