Visual Basic Activities - If Then Else
Visual Basic Activities - If Then Else
2
We modified the code in Example 13.1 by deleting the second If statement and use the
Else keyword instead. When you run the program and enter a number that is greater
than 100, the me=ssage “Congratulation! You win a lucky prize” will be
shown.Otherwise, you will see the "Sorry, You did not win any prize" message, as
shown in Figure 13.3
The code
Private Sub OK_Click(sender As Object, e As EventArgs)
Handles OK.Click
Dim myNumber As Integer
myNumber = TxtNum.Text
If myNumber >= 50 And myNumber < 100 Then
MsgBox( "Congratulation! You win a lucky prize")
Else
MsgBox( "Sorry, You did not win a lucky prize")
End If
End Sub
Example 13.3
This program involves using two variables and two conditions. Both conditions must be
met otherwise the second block of code will be executed. In this example, the number
entered must at least 100 and the age must be at least 60 in order to win a lucky prize,
any one of the above conditions not fulfilled will disqualify the user from winning a prize.
You need to add another text box for the user to enter his or her age. The output is as
shown in Figure 13.4
The Code
Private Sub BtnShow_Click(sender As Object, e As EventArgs)
Handles BtnShow.Click
Dim grade As String
grade = TxtGrade.Text
Select Case grade
Case "A"
MsgBox("High Distinction")
Case "A-"
MsgBox("Distinction")
Case "B"
MsgBox("Credit")
Case "C"
MsgBox("Pass")
Case Else
MsgBox("Fail")
End Select
End Sub
The Output
Example 14.2
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles
Button1.Click’Examination Marks
Dim mark As Single
mark = mrk.Text
Select Case mark
Case Is >= 85
MsgBox( "Excellence")
Case Is >= 70
MsgBox( "Good")
Case Is >= 60
MsgBox( "Above Average")
Case Is >= 50
MsgBox( "Average")
Case Else
MsgBox( "Need to work harder")
End Select
End Sub
Example 14.3
Example 14.2 can be rewritten as follows:
‘Examination Marks
Dim mark As Single
mark = Textbox1.Text
Select Case mark
Case 0 to 49
MsgBox( "Need to work harder")
Case 50 to 59
MsgBox( "Average" )
Case 60 to 69
MsgBox( "Above Average")
Case 70 to 84
MsgBox( "Good")
Case 85 to 100
MsgBox("Excellence")
Case Else
MsgBox( "Wrong entry, please reenter the mark")
End Select
End Sub
Example 14.4
Grades in high school are usually presented with a single capital letter such as A, B, C,
D or E. The grades can be computed as follow:
Figure 14.3