Conditional Logic – If Statements

Number of View: 3

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:

If I 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 little If 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.

  1. The first line contains our condition: “If the following condition is met”.
  2. The second line is what we want to do if the condition is indeed met.
  3. 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.

VN:F [1.9.10_1130]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.10_1130]
Rating: 0 (from 0 votes)

Popularity: unranked

Select Case Statements

Number of View: 3

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” adn click your button. next, try the word “eaten”, with a lowercase “e”.

So, how does the Select case work?

Int he 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

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. We’ll do that in the next section.

VN:F [1.9.10_1130]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.10_1130]
Rating: 0 (from 0 votes)

Popularity: unranked

Coding the Plus Button

Number of View: 0

Let’s remind ourselves how our calculator from the previous section works works. To add up 5 + 9, we’d do this:

  1. Click first on the 5
  2. A 5 appear in the textbox
  3. Click the + symbol
  4. The 5 disappears from the textbox
  5. Click on the number 9
  6. A 9 appears in the textbox
  7. Click on the = symbol
  8. The 9 disappears from the textbox
  9. The answer to 5 + 9 appears in the textbox
  10. Click the “Clear” button to clear the textbox

We’ve done numbers 1 and 2 on that list. We’re now going to do numbers 3 and 4 on the list. What we’re trying to do is this: Click on the Plus symbol and make the number in the Textbox disappear. Before the number vanishes, we can store it in a variable. The variable we’re going to be storing the number in is one of those variable we set up at the top of the code. It’s this one:

Dim total1 As Integer

We’ve already seen how to retain a value from a textbox and add it to something else:

txtDisplay.Text = txtDisplay.Text & btnZero.Text

Here, we kept the value that was already in the textbox and joined it to the Text property of the button.

We can do something similar if we want to retain a value that is already in a variable. Examine this:

variable1 = variable1 + 1

The “= variable1 + 1” part just says “Remember what is in the variable variable1, and then add 1 to it. So if variable1 contain the number 3, what would variable1 now hold after that bit of code is executed? The whole code might be this

variable1 = 3
variable1 = variable1 + 1

(If you don’t know the answer to that, please send an email and ask for some further clarification on the subject.)

The above is known in programming terms as “Incrementing a variable”. There is even a shorthand you can use:

variable1 += 1

This says “variable1 equals variable1 plus 1″. Or “Add 1 to variable1″. You can also use the other mathematical operators with the same shorthand notation:

variable1 = 10
variable1 *= 3

This new code says “Multiply whatever is inside of variable1 by 3″.

The shorthand notation can be tricky to read (and to get used to), so we won’t use it much. But it’s there is you want it.

 

Back to our code.

If we’re going to be adding two numbers together, we need Visual Basic to remember the first number. Because when we click the equals sign, that first number will be added to the second number. So if we haven’t asked VB to remember the first number, it won’t be able to add up.

The variable we’re going to be storing the first number in is total1. We could just say this:

total1 = txtDisplay.Text

Then whatever is in the textbox will get stored in the variable total1.

Except we want VB to remember our numbers. Because we might want to add three or more numbers together: 1 + 2 + 3 + 4. If we don’t keep a running total, there’s no way for our programme to remember what has gone before, it will just erase whatever is in total1 and then start again.

So just like the code above (varaible1 = variable1 + 1), we need to “tell” our programme to remember what was in the variable. We do it like this:

total1 = total1 + Val(txtDisplay.Text)

That Val( ) part just makes sure that a number in a textbox is kept as a number, and not as text. It’s short for Value. The important part is the total1 + txtDisplay.Text. We’re saying “The variable total1 contains whatever is in total1 added to the number in the textbox.” An example might clear things up. Suppose we were adding 5 + 9. Now, suppose total1 already contained the number 5, and that number 9 was in the textbox. It would work like this:

Finally, we need to erase the number in the textbox. To erase something from a textbox, just set its Text property to a blank string. We do this with two double quotation marks. Like this:

txtDisplay.Text = “”

That tiny bit of code will erase the Text a textbox. Another way to erase text from a textbox is to use the Clear method. After you typed a full stop, you probably saw the drop down list of Properties and Methods. Scroll up to the top, and locate the word Clear. Double click “Clear” and the drop down list will close. Hit the return key and VB adds two round brackets to your code:

txtDisplay.Clear( )
Notice that we’re not setting the textbox to equal anything. We’re using something called a Method. You can tell it’s a Method because there’s a purple block icon next to the word. A Method is a built-in bit of code that VB knows how to execute. In other words, it knows how to clear text from a textbox. You’ll learn more about Methods later.

So the whole code for our Button called btnPlus is this:

Private Sub btnPlus_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles btnPlus.Click

total1 = total1 + Val(txtDisplay.Text)

txtDisplay.Clear()

End Sub
Add that code to your Plus button. All we’ve done with that code is to store numbers into our variable total1 and then erase whatever was in the textbox.

We now need to add the numbers up.

Exercise

Write the code for the equals button. There’s only three lines in total, and here’s a little help.

You need to use the other variable that was set up at the top of the coding window, total2. The variable total1 will be added to whatever is total2

The first line of code will be this

total2 = total1 + (something missing here)

Your job is to supply the missing code. In other words, replace “(something missing here)”

Remember that total1 contains the first number to be added. And you know where that came from. The only thing left to do is to add the second number.

For the second line of code, you need to transfer the total2 variable to the textbox.

For the third line of code, all you are doing is resetting the variable total1 to zero. That’s because after the equals button has been pressed, we have finished adding up. If you wanted to do some more adding up, that total1 will still hold the value from the last time. If you reset it to zero, you can start adding some new numbers.

The only thing left to do is to write a single line of code for the Clear button. All you are doing there is erasing text from a textbox. Which you already know how to do.

When you’re finished, you should have a simple calculator that can add up integers. In the next section, we’ll take a look at Conditional Logic, and why it’s so important for your programming skills.

VN:F [1.9.10_1130]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.10_1130]
Rating: 0 (from 0 votes)

Popularity: unranked