The If Statement

Conditional statements make up the backbone of programming. Without them our programs would just be like videos, running through exactly the same each time. So far all of the conditional parts of our programming has been hidden away, done for us by Visual Basic. For example we had to detect if they pressed the button on the form in the earlier tutorials. Conditional programming was also used to detect what keys they pressed when they typed into the text box.
In this tutorial we will be using our own conditional statements to check a users password.

The Syntax


The Syntax for an If statement is:
If Condition Then Statement

Or
If condition Then
Statement 1
Statement 2
Else
Statement 3
Statement 4
End If

I prefer the second as it is clearer and it is easier to add extra statements and Else. The first statements are executed if the condition are true and the third and fourth are executed if the condition is false.

The Condition

This would be a good point to reopen your project from tutorial 2. You will need to change the labels caption to 'Type the password in the box'(you may need to resize it) and the button caption to 'Enter'.

There are 6 comparison operators that you will need to know. The two which can be used with any variables are:
'=' equal to
'<>' not equal to
They are pretty self explanatory. They return true or false. There are four numerical comparison operators:
'>' greater than
'<' less than
'>=' greater than or equal to
'<=' less than or equal to

Boolean expressions make a whole condition by themselves as they contain a true or false value already.

Now go to your program and double click the command buttton to get its click event up. Delete the code thats already in the sub. Now we are going to enter this If statement:
If Text1.Text="the password" Then
    MsgBox "Congratulations you solved the riddle!"
Else
    MsgBox "Check the instructions more carefully"
End If


Now run the program and see if anyone can work out what to do.

More complex conditions

You can use Boolean algebra to combine two conditions into one. You can use 'Not', 'And', 'Or' and 'Xor'. This are like the logic gates. Don't worry if you haven't heard of logic gates its quite simple.

Basically you put two expressions with 'And', 'Or' or 'Xor' in between. If you use and then the expression is true if the first AND the second is true. If you use or then it returns true if the first one OR the second is true (including both true) with XOR(exclusive or) if one or the other is true then it is true (but not both). The Not can be used with an expression to reverse its value. Brackets can be used to set precedences.


© Jonathan Waller 2005; QuantumState Visual Basic