Decisions in Visual Basic

This week’s article will deal with decision making in Visual Basic.

As you all know, computers are great for calculations. We already saw the possibility to add, subtract, multiply, and divide numbers. That’s all very nice, but at times we need to compare numbers with another (is b bigger than c?), string with one another (did the user supply the proper username and password?) etc.

I’ll introduce you to the If… Then… Else… and Select Case statements today.

If… Then… Else…

If… Then… Else… is used when you need to make a decision. Computer are very bad at making decisions. Ask a computer “Where should I go, Left, or Right?”, and your puter will prolly just sit there. If you’re in bad luck, and your puter had a bad day, it might start smoking. Computers are very good though at evaluating things though. As far as a computer is concerned, the whole wide world is built up out of 1’s and 0’s. A computer can test whether something is True or False. A value of 0 would be False. Logically speaking, True would be a 0. However, in VB6, True is -1. Don’t worry about why, just remember that a value of False equals a 0. (VB.NET recognizes 1 as True).

To evaluate whether or not something is True or False, we can use the If… Then…. Statement.

The Syntax for this statement is:

If condition Then

Visual Basic will evaluate whether or not the condition you specified was met. An example here could be:

Dim x as Integer

x = 6

If x <> 5 Then
Msgbox “The value of x = ” & x
End If

What do we actually do here? First we declare a variable x, then we set the value of x to 6.

Next, we use an IF statement to check if X is more or less than 5. In other words, we check if x is NOT 5. (If a value is smaller or bigger than the value you’re looking for, it is not equal to it).

If the value of x is different, than we make Visual Basic give us a MessageBox with the value of x in it. If you would set the value of x to 6, instead of 5, you would not see a MessageBox at all.

All right, so where’s the ‘Else’ statement then? We’ve just seen an ‘If’ statement here. Let’s enhance the earlier code a little.

Dim x as Integer

x = 6

If x <> 5 Then
Msgbox “The value of x = ” & x
Else
MsgBox “x = 5”
End If

It’s not hard to see what’s happening here. The code we added will make a MessageBox appear if x equals 5. Change x to 5 in the code, and rerun the program to see the new MessageBox.

The If-statement can be enhanced by using the ‘ElseIf’ function. For demonstration purposes, get a new form, and create a TextBox and a CommandButton on it. This is where we will take an inputnumber from the user. Change the caption of the CommandButton to ‘Guess!’, the Form’s caption to ‘A number guessing game’, and remove the initial text from the TextBox. Double-click the CommandButton, and add the following code:

Dim intOurNumber as Integer

intOurNumber = 10

If intOurNumber > Text1 Then
MsgBox “Guess higher”
ElseIf intOurNumber < Text1 Then MsgBox "Guess lower" Else MsgBox "Congratulations, you guessed our number" End If What we did here should be quite obvious. If the user guessed too low, we'll tell him so. Likewise, when he guessed too high, he'll be told so. If he guessed correctly, we congratulate him on guessing the correct number. Our first If-statement evaluates whether the value was too low. The ElseIf-statement checks too see if the number was too high. Finally, the Else-statement determines all other possible options (If the number is not higher, and the number is not higher, it must be the correct number, right?). One word of warning. Please do NOT forget to 'close' the If-statement by using 'End If'. You will get an error when you try to run the program. If-statements can be nested. This basically means that within an If-statement, you could create another If-statement. This could be useful once you start writing some more advanced programs. For now, I'll just give you a hypothetical example: If x > 5 And x < 10 Then ' x is between 5 and ten If x > 7 and x < 9 Then ' x must be 8 MsgBox x End If End If So far, we've only seen comparisons with numbers, but you could just as well evaluate String Functions. Let's also try out something with that. Create a new form, and call it 'Login'. On the form, create two TextBoxes and a CommandButton. Use the following schema.

Basically, we’re creating a very, very basic version of a loginscreen. This is not a very secure one though!

Double-click on the button, and insert the next code:

MsgBox “Wrong credentials”
Else
MsgBox “Wrong credentials”
Else
MsgBox “Welcome!”
End If
End If

All right. We’ve seen how we can use the If-statement to evaluate a few possible options. Usually, we use If-statements if the possibilities are few (I.e. Either true, false, and maybe an ‘Else’ for everything else). What though if we want to evaluate multiple conditions? Like… Days of the week? Or friend names? Dates?

If you need to compare multiple possible options, the Case-Statement is a better way than using the If-statement. The reason for this is that with If-statements, even if at one point you reached the ‘True condition’, VB will still look for other possibilities. This can have an impact on performance if you need to look for a particular value out of a lot of possible combinations.

Case

Suppose we’re writing a program that deals with a yearly calendar. On special holidays, we’ll want a notification to be sent (we’ll again use a MessageBox for this purpose).

The dates we want to use.
We have 5 dates there. Normally, that would require 5 different IF statements to evaluate whether or not one was today’s date. Even if it found the correct date, unless you’d make the function end at that point, it would require quite a bit of code.

The Case-statement offers a nice solution. It’s syntax is rather straightforward. You start with a Select Case statement, and then supply the string you want to evaluate, and then you list off the possible values using Case-statements.

Create a new project in VB, add a button, and double-click the button. There, add the following code:

Dim intDate

intDate = Day(Now()) & “-” & Month(Now())

Select Case intDate
Case “1-1”
MsgBox “January 01. Happy new year”
Case “4-7”
MsgBox “July 4th! Happy independence day!”
Case “11-9”
MsgBox “A tragic day in world’s history”
Case “31-10”
MsgBox “Trick or treat! Happy Halloween!”
Case “25-12”
MsgBox “Happy christmas!”
Case Else     MsgBox “Nothing special today” End Select

Note I used the European date/time settings here. However, this will run fun on any machine anywhere in the world. The reason for this is that both the Day() and Month() Functions take their part (they respectively retrieve the day- and month-part out of a given date. In this particular case, we use Now() which returns the current system date) from the Regional Settings of the computer.

The code takes the day-part of the current system date (which can be found using Now()), adds a hyphen (‘-‘), and then adds the month-part of the current system date. It then uses the select case statement to check whether that is the same as whatever we want to check.

You can check to see if the program works by changing your computer’s system time. Run the program, and then click the button. you’ll be greeted with the pop-up message applying to whatever date you picked. You can add your own dates to the list, and use it for whatever you’d like, really.