Conditional Logic - If Statements
What is conditional logic? Well, it's something you use in your daily life all the time, without realising you're doing it. Suppose that there is a really delicious cream cake in front of you, just begging to be eaten. But you are on a diet. The cake is clearly asking for it. So what do you do, eat the cake and ruin your diet? Or stick to your diet and let somebody else have that delicious treat? You might even be saying this to yourself:
IfI eat the cake Then my diet will be ruined
If I don't eat the cake Then I will be on course for a slimmer figure
Note the words If and Then in the above sentences. You're using conditional logic with those two words: "I will eat the cake on condition that my diet is ruined". Conditional logic is all about that littleIf word. You can even add Else to it.
If I eat the cake Then my diet will be ruined
Else
If I don't eat the cake Then I will be on course for a slimmer figure
And that is what conditional Logic is all about - saying what happens if one condition is met, and what happens if the condition is not met. Visual Basic uses those same words - If, Then, Else for conditional Logic. Let's try it out.
Start a new project. Give it any name you like. In the design environment, add a Button to the new form. Double click the button and add the following code to it:
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles Button1.Click
Dim firstname As String
firstname = "Bill"
If firstname = "Bill" Then MsgBox("firstname is Bill")
End Sub
Run the programme and see what happens. You should get a Message Box with the words "firstname is Bill" in it.
What we did was to set up a string variable and put the name "Bill" into it. When then used conditional logic to test what was in the variable. In fact, we used an If statement. We said:
If the variable called firstname holds the value "Bill" Then display a Message Box
We can tidy that up a bit, because a single line of code can get very long with If statements. We can use this format instead.
If firstname = "Bill" Then
MsgBox "firstname is Bill"
End If
That's a lot tidier. Note that we start a new line after the word Then.
- The first line contains our condition: "If the following condition is met".
- The second line is what we want to do if the condition is indeed met.
- The third line tells Visual Basic that the If statement ends right here.
Try this. Delete the two quotation marks around the word Bill in the If Statement. Your code should now be this:
Dim firstname as String
firstname = "Bill"
If firstname = Bill Then
MsgBox "firstname is Bill"
End If
VB.NET puts a blue wiggly line under Bill. If you try to start your programme, you'll get a message box telling you that there were Build Errors, and asking if you want to continue.
Say No to return to the design environment. The reason for the blue wiggly line is that VB insists on you using double quotes to surround you text. No double quotes and VB insists it's not a string of text.
Change you code to this.
firstname = "Phil"
If firstname = "Bill" Then
MsgBox "firstname is Bill"
Else
MsgBox "firstname is not Bill"
End If
Now run the programme and see what happens when you click the button.
You should have gotten a Message Box popping up saying "firstname is not Bill". The reason is that we included the Else word. We're now saying, "If the condition is met Then display one Message Box. If the condition is not met, display a different Message Box." Notice that the Else word is on a line of it's own.
Now, after you have tested your programme, try this. Add a textbox to your form. Then change this line in your code:
firstname = "Phil"
To this:
firstname = Textbox1.Text
What the code does is to transfer the text in the Textbox directly to the firstname variable. We can then test what is in the variable with an If statement.
When you've finished the code, test it out by typing the word "Bill" (with a capital B) into the textbox, and then clicking the button. Then try it with a lower case "b".
So far, we've explored only simple If statements, and we're going to leave it that way for now. But they can get quite complex, because you can have one If statement inside another, and multiple Else statements.
The code you have just wrote, however, does demonstrate how you can find out what is in a variable, and take action if the condition is either met or not met. We're now going to explore another way to do that - the Select Case statement.
Select Case Statements
The Select Case statement is another way to test what is inside of a variable. You can use it when you know there is only a limited number of things that could be in the variable. For example, suppose we add another choice for that cream cake. We've only said that the consequences of eating the cream cake is that the Diet will be either "Ruined" or "Not Ruined". But what if we add another option - "Diet Not Tested". In other words, we ate the cake but refused to climb onto the scales to weigh ourselves!
With three choices, we can still use an If ... Else statement. But let's change it to a Select Case statement. Remember: all we are doing is testing what is inside a variable, in this case a variable called creamcake. Once we decide what is inside the variable, we can take some action. So let's look at how the Select Case works.
Create a Form with a button and a Textbox on it (If you have your form open from the previous section, then you can use this one). Double click the new button. You should see something like this appear.
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles Button1.Click
End Sub
Between the button Sub and End Sub code add the folowing
Dim creamcake As String
Dim DietState As String
creamcake = TextBox1.Text
Select Case creamcake
Case "Eaten"
DietState = "Diet Ruined"
Case "Not Eaten"
DietState = "Diet Not Ruined"
Case Else
DietState = "Didn't check"
End Select
MsgBox DietState
Run your code to test it out. Click inside your textbox and enter the word "Eaten". Then click your button to see what happens. Now enter the words "Not Eaten" and click your button. Next, try the word "eaten", with a lowercase "e".
So, how does the Select case work?
In the code above, we first set up two variables called creamcake and DietState. Next, we transfer whatever is in Textbox1 to the variable creamcake. The Select Case begins on the next line:
Select Case creamcake
We tell Visual Basic that we want to start a Select Case statement by simply using the words "Select Case". This is enough to set up the statement. The variable creamcake follows the words Select Case. We're saying, "Set up a Select Case statement to test what is inside the variable called creamcake". The next line is this:
Case "Eaten"
We ask Visual Basic to check if the variable creamcake contains the word "Eaten". (Is it the Case that ... ?)
If it is the Case that creamcake contains the word "Eaten", then VB will drop down to the line or lines of code below and read that. If the variable creamcake doesn't contain the word "Eaten", the programme will skip the line or lines of code below and jump to the next Case.
The programme will continue to check all the words after Case to see if one of them contains what is in the variable creamcake. If it finds one, it will read the code below the Case word; if it doesn't find any matches, it will not do anything at all. In our code, we're checking these three Cases:
Case "Eaten"
Case"Not Eaten"
Case Else
Note also that it will only look for an exact match - "Eaten", but not "eaten".The next line to examine is this:
Case Else
You can use the Else word after Case. If the programme hasn't found any matches, it will then execute the code below the Case Else line.
The final line to examing is this:
End Select
All we're doing here is to tell Visual basic to end the Select Case statement.
So the Select Case checks a variable for any number of different choices. If a match is found, it will then execute code below the Case option it has found. In our code, we've just told the programme to store some text in the DietState variable. After the Select Case statement has ended we displayed the variable in a Message Box.
You can use Select Case statement with numbers, as well, and the To word comes in very handy here. If you were checking a variable to see if the number that was in the variable fell within a certain age-range, you could use something like this:
Select Case agerange
Case 16 To 21
MsgBox “Still Young”
Case 50 To 64
MsgBox “Start Lying”
End Select
Here, a variable called agerange is being tested. It's being checked to see if it falls between certain values. If it does, then a message box is displayed.
Exercise G
Add a new button to your form. Write a programme that tests if a person is a) A teenager, b) in their twenties, c) in their thirties, or d) none of the above.
A popular way to use Select Case statements is with a drop down box. You can then test which item a user selected from a list of available items. You're going to write a little programme to do just this. But before you can do so, you'll need to know how to add a Combo Box to a form, and how to get at the values in its list.
Add a Combo Box to a VB .NET form
Create a new project for this section. Add a button to your new form. Then, locate the Combo Box on the Visual Basic .NET toolbar. It looks like this:
Double click the icon to add a Combo Box to your form. Or click once with the left hand mouse button, and then draw one on the form.
A combo box is a way to limit the choices your user will have. When a black down-pointing arrow is clicked, a drop down list of items appears. The user can then select one of these options. So let's set it up to do that.
- Click on your Combo Box to select it. Then locate the Item property from the Properties Box:
- Click the grey button, as above. The one with the three dots in it. When you do, you'll get the following box popping up:
- To use the String Collection Editor, type an item and press Return (it's just like a normal textbox. Each item will be one item in your drop-down box.)
- Enter five items, as in the image below:
- Then click the OK button at the bottom.
The Editor will close, and it will look like nothing has happened. However, run your programme and test out your new Combo Box. You should have something like this:
You now need to know how to get values from the list. Once you know how to get a value from the list, you can put the value into a variable and test it with some Conditional logic.
Getting a value from a Combo Box is fairly straightforward, because it acts just like a Textbox. A Textbox has a Text property, and so does a Combo Box. To get a value from a Textbox, you would code like this
MyVariable = Textbox1.Text
Whatever is in the Textbox will be transferred to the variable called MyVariable. The process is exactly the same for a Combo Box. The code is like this:
MyVariable = Combobox1.Text
Now we are transferring whatever is selected from the Combo Box to the variable called MyVariable.
Let's try it. Double click the button you added to your form. This will open the code window. Then enter the following code for the button:
Dim MyVariable as String
MyVariable = Combobox1.Text
MsgBox MyVariable
Run your programme. When the programme is running, select an item from your Combo Box. Then click your button. Whatever was in the Combo Box window should have ended up in the Message Box.
And that's all there is to getting a value from a Combo Box - just access its Text Property and pass it to a variable.
Finally, the Combo Box has a DropDownStyle property. Locate this property and you'll notice its value has a drop down box. The box contains three different Combo Box styles to choose from. Experiment with all three and see how they differ.
Conditional Operators
The Conditional Operators allow you to refine what you are testing for. Instead of saying "If X is equal to Y", you can specify whether it's greater than, less than, and a whole lot more. Examine the list of Operators:
A word about And and Or. Notice the format with And and Or. The variable is repeated twice
If VariableName= 7 Or VariableName= 10 Then MsgBox "7 or 10 spotted"
If you just put something like this
If VariableName> 7 Or < 10 Then MsgBox "7 or 10 spotted"
then Visual Basic will give you an error message. What you have to say is
If [test the variable for this value] And [test the variable for that value] Then
Your If statement can contain an Else part, too. The format is this:
If [conditional logic here] Then
Some Code here
Else
Some Other Code here
End If
But don't worry if all that hasn't sunk in - you'll get used to the Conditional Operators as you go along. In the next part, there's two little programmes for you to write. They will test the skills you have acquired so far.
Section Three Exercises
Part 1 - If statements
Start a new project. Add a textbox, a Label and a button to your new Form. Then write a programme that does the following:
- Asks users to enter a number between 10 and 20.
- The number will be entered into the Textbox.
- When the Button is clicked, your Visual Basic code will check the number entered in the Textbox.
- If it is between 10 and 20, then a message will be displayed.
- The message box will display the number from the Textbox.
- If the number entered is not between 10 and 20 then the user will be invited to try again, and whatever was entered in the Textbox will be erased
Part 2 - Select Case Statements
Add a Combo box and another button to your form. Create a list of items for your Combo Box. The list of items in your Combo box can be anything you like - pop groups, football teams, favourite foods, anything of your choice. Then try the following:
Use a select case statement to test what a user has chosen from your drop-down list. Give the user a suitable message when the button was clicked.
In the next section of this course, we'll move on to loops in Visual Basic .NET.
Comments
Post a Comment