In any programming language, we come across the sentence "If
something occurs, then do this else do that." This is what being
done using if statement in Visual Basic.
There are six forms of If condition in visual basic,
Form - 1
If [[condition]] Then [statement]
|
Form - 2
If [[condition]] Then [statement] Else [statement]
|
Form - 3
If [condition] Then
[statements]
End If
|
Form - 4
If [condition] Then
[statements]
Else
[statements]
End If
|
Form - 5
If [condition] Then
[statements]
ElseIf [condition] Then
[statements]
End If
|
Form - 6
If [condition] Then
[statements]
Else
If [condition] Then
[statements]
End If
End If
|
Whenever Visual Basic encounters if statement, it will test for the
condition given there. If the condition becomes true, then Visual
Basic will execute the statements proceeds “Then”. Else
it will test for another condition and so on, till the last “Else”
is encountered.
The first two if statements are meant to be written in single line
only. There should not be more than one statement to be executed for
writing these two single lined if statements.
The rest of the If statements are written in multiple lines. A mismatch
in the syntax could cause the Visual Basic interpreter to point out
the mistake, when you hit the enter key at the end of the line in
the Visual Basic IDE. An error message will be flashed out to the
developer.
Let us now, look into examples.
For our example to work, choose a text box and a Command Button from
Tool Box.
Type the given code in click event of the command button at the code
window
If Text1.Text = “PBS” Then MsgBox “Programming Basics...”
|
And Run the program in the Visual Basic IDE itself by pressing F5.
Next, Type “PBS” in the text box and click on
the command button. It will show up a message box with OK
button as “Programming Basics !...”. Typing something
else will display nothing because of if condition in the click
event of command button.
If you want to display "Wrong Cmd !...", when
you type something else then you should modify the above code
as,
If Text1.Text = “PBS” Then MsgBox “Programming Basics !...” Else Msgbox ”Wrong Cmd !...”
|
The above code can also be written in multi line, as,
If Text1.Text = “PBS” Then
MsgBox “Programming Basics !...”
Else
Msgbox ”Wrong Cmd !...”
End If
|