Visual Basic 2005 Guide
Selection - The If Statement
Selection
Selection means writing code that will only be run when a condition is true or false. There are many ways to do this in Visual Basic.
- If Then
- If Then ... Else
- If Then ... ElseIf
- Select Case
The following relational operators can be used to create expressions that evaluate to true or false.
< | is less than |
> | is greater than |
= | is equal to |
<= | is less than or equal to |
>= | is greater than or equal to |
<> | is not equal to |
If Then
Try the following example code in a new project containing a text box called txtAge and a command button called btnCanDrive
Private Sub btnCandrive_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCandrive.Click
Dim intAge As Integer
intAge = txtAge.Text
If intAge gt; 16 Then
MsgBox "You are old enough to drive."
End If
End Sub
Study the lines of code carefully. The first line declares a variable to stored the age. The second line sets this variable to be equal to the number entered in the text box. You will only see the message box if you enter a number above 16. This means that the line of code that does this only runs when intAge > 16. Notice that we have to write End If at the end of this programming construct.
If Then ... Else
Try out the following. Note that you will now get a message box if you are too young as well as if you are old enough.
Private Sub btnCandrive_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCandrive.Click
Dim intAge As Integer
intAge = txtAge.Text
If intAge > 16 Then
MsgBox "You are old enough to drive."
Else
MsgBox "You are too young to drive."
MsgBox "Sorry, Barry."
End If
End Sub
If Then ... ElseIf
Let's move things on a little bit. Try out the following.
Private Sub btnCandrive_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCandrive.Click
Dim intAge As Integer
intAge = txtAge.Text
If intAge > 16 Then
MsgBox "You are old enough to drive."
ElseIf intAge = 16 Then
MsgBox "You can drive next year."
Else
Msgbox "You are way too young for driving."
End If
End Sub