CHAPTER 4. CONTROLLING THE FLOW

Provided by:  Thearon Willis, Bryan Newsome

Beginning Microsoft Visual Basic 2010

This topic contains the following sections.

  • Making Decisions
  • The If Statement
  • Select Case
  • Loops
  • Summary
  • Exercise

Making Decisions

Algorithms often include decisions. It’s this decision-making ability that makes computers do what they do so well. When you’re writing code, you make two kinds of decisions. The first kind is used to find out what part of an algorithm you’re currently working on or to cope with problems. For example, imagine you have a list of 10 people and need to write a piece of code to send an e-mail to each of them. To do this, after sending each e-mail, you ask, "Have I finished?" If so, you quit the algorithm; otherwise, you get the next person in the list. As another example, you might need to open a file, so you ask, "Does the file exist?" You have to deal with both possible answers to that question.

The second kind of decision is used to perform a different part of the algorithm depending on one or more facts. Imagine you’re going through your list of 10 people so that you can send an e-mail to those who own a computer, but telephone those who don’t. As you look at each person, you use the fact that the person does or doesn’t own a computer to choose what you should do.

These decisions are all made in the same way, and it doesn’t matter whether you have more of the first kind, more of the second kind, or whatever. Now, let’s take a look at how to make a decision using the If statement.

The If Statement

The simplest way to make a decision in a Visual Basic 2010 program is to use the If…Then statement. You learn to use an If…Then statement in the following Try It Out exercise.

Let's look at the If…Then statement.

  1. Create a Windows Forms Application project called Simple If. Add a Button control, setting its Name property to btnIf, and its Text property to If. Double-click the button and add the following bolded code:

    Private Sub btnIf_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles btnIf.Click
        ‘Declare and set a variable
        Dim intNumber As Integer = 27
    
        ‘Here's where you make a decision,
        ‘and tell the user what happened
        If intNumber = 27 Then
            MessageBox.Show(″'intNumber' is, indeed, 27!″, ″Simple If″)
        End If
    End Sub
    
  2. Save your project and then run it. Click the If button and you’ll see the message box shown in Figure 4-1.

    intNumber is, indeed, 27!

    FIGURE 4-1

In this example, first you declare an Integer variable called intNumber and set its value to 27, all in the same line of code, as shown here:

‘Declare and set a variable
Dim intNumber As Integer = 27

Then you use an If…Then statement to determine what you should do next. In this case, you say, "If intNumber is equal to 27…":

‘Here's where you make a decision,
‘and tell the user what happened
If intNumber = 27 Then
    MessageBox.Show(″'intNumber' is, indeed, 27!″, ″Simple If″)
End If

The code block that follows this will be executed only if intNumber equals 27. You end the code block with End If. Anything between If and End If is called only if the expression you’re testing for is true.

So, as you walk through the code, you get to the If statement, and it’s true. You drop into the code block that runs if the expression is true, and the text is displayed in a message box.

Note

Notice that the code within the If…End If block is automatically indented for you. This is to increase readability so that you can tell what code will run in the event that the condition is true. It’s also good to add some whitespace before the If…Then statement and after the End If statement to enhance readability further.

A simple If block like the previous one may also be written on one line, without an End If statement:

If intNumber = 27 Then MessageBox.Show(″'intNumber' is, indeed, 27!″,
   ″Simple If″)

This works equally well—although you are limited to only one line of code within the If statement. Now you know what happens if your condition is true; but what happens if you fail the test and the result is false? You find out in the next Try It Out.

In this example, you will see how to code for when the If statement is not true.

  1. Return to the Forms Designer for the Simple If program. Add another Button control to the form and set its Name property to btnAnotherIf and its Text property to Another If. Double-click the button and add the following bolded code:

    Private Sub btnAnotherIf_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles btnAnotherIf.Click
    
            ‘Declare and set a variable
            Dim intNumber As Integer = 27
    
            ‘Here's where you make a decision,
            ‘and tell the user what happened
            If intNumber = 1000 Then
                MessageBox.Show(″'intNumber' is, indeed, 1000!″, ″Simple If″)
            End If
    End Sub
    
  2. Run your project and click the Another If button; nothing will happen.

Tip

In this case, the question "Is intNumber equal to 1000?" comes out false. The code block executes only if the statement is true, so it’s skipped. If the statement were true, the line between the If and End If lines would have executed. However, in this instance the statement was false, so the next line to be executed was the first line directly following the End If line (which is End Sub). In effect, the true code block is skipped.

The Else Statement

If you want to run one piece of code if the condition is true and another piece if the condition is false, then you use the Else statement. This expands on the previous Try It Out.

This Try It Out builds on the previous Try It Out to show how the Else statement works.

  1. Return to the Code Editor in the Simple If project and modify the code in the btnAnotherIf_Click procedure so that it looks like this:

    Private Sub btnAnotherIf_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles btnAnotherIf.Click
    
        ‘Declare and set a variable
        Dim intNumber As Integer = 27
    
        ‘Here's where you make a decision,
        ‘and tell the user what happened
        If intNumber = 1000 Then
            MessageBox.Show(″'intNumber' is, indeed, 1000!″, ″Simple If″)
        Else
            MessageBox.Show(″'intNumber' is not 1000!″, ″Simple If″)
        End If
    End Sub
    
  2. Run the project and you’ll see the message box shown in Figure 4-2.

    intNumber is not 1000!

    FIGURE 4-2

Tip

Here, the code following the Else statement runs if the condition in the If statement is not met. In this case, the value of intNumber is 27, but the condition being tested for is intNumber = 1000, so the code after the Else statement is run:

MessageBox.Show(″'intNumber' is not 1000!″, ″Simple If″)

Allowing Multiple Alternatives with ElseIf

If you want to test for more than one condition, you need to make use of the ElseIf statement.

In this Try It Out, you’ll use your Simple If program to see how you can test for the value of intNumber being 27 and 1000.

  1. Return to the Code Editor and change the code in the btnAnotherIf_Click procedure so that it looks like this:

    Private Sub btnAnotherIf_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles btnAnotherIf.Click
    
        ‘Declare and set a variable
        Dim intNumber As Integer = 27
    
        ‘Here's where you make a decision,
        ‘and tell the user what happened
        If intNumber = 1000 Then
            MessageBox.Show(″'intNumber' is, indeed, 1000!″, ″Simple If″)
        ElseIf intNumber = 27 Then
            MessageBox.Show(″'intNumber' is 27!″, ″Simple If″)
        Else
            MessageBox.Show(″'intNumber' is neither 1000 nor 27!″, ″Simple If″)
        End If
    End Sub
    
  2. Run the project and click the Another If button. You’ll see the message box shown in Figure 4-3.

    intNumber is 27!

    FIGURE 4-3

Tip

This time the code in the ElseIf statement ran because intNumber met the condition intNumber = 27. Note that you can still include the Else statement at the end to catch instances where intNumber is neither 27 nor 1000, but something else entirely:

ElseIf intNumber = 27 Then
    MessageBox.Show(″'intNumber' is 27!″, ″Simple If″)
Else
    MessageBox.Show(″'intNumber' is neither 1000 nor 27!″, ″Simple If″)

End If

Note

You can add as many ElseIf statements as you need to test for conditions. However, bear in mind that each ElseIf statement is executed as Visual Basic 2010 attempts to discover whether the condition is true. This slows your program if you have a lot of conditions to be tested. If this is the case, you should try to put the statements in the order they are most likely to be executed, with the most common one at the top. Alternatively, you should use a Select Case block, which you will be looking at later in the chapter.

Nested If Statements

It’s possible to nest an If statement inside another:

If intX = 3 Then
    MessageBox.Show(″intX = 3″)

   If intY = 6 Then
       MessageBox.Show(″intY = 6″)
   End If

End If

There’s no real limit to how far you can nest your If statements. However, the more levels of nesting you have, the harder it is to follow what’s happening in your code, so try to keep the nesting of If statements to a minimum.

Single-Line If Statement

The single-line form of the If statement is typically used for short, simple tests, and it saves space in the code editor. However, it doesn’t provide the structure and flexibility of the multiline form and is usually harder to read:

If intX = 3 Then MessageBox.Show(″intX = 3″) Else MessageBox.Show(″intX is not 3″)

You don’t need an End If at the end of a single-line If…Then statement.

Multiple statements can also be executed within a single-line If…Then statement. All statements must be on the same line and must be separated by colons, as in the following example:

If intX = 3 Then MessageBox.Show(″intX = 3″): intX = intX + 1: Total += intX

Comparison Operators

You know how to check whether a particular variable is equal to some value and execute code if this is the case. In fact, If is far more flexible than this. You can ask questions such as these, all of which have yes/no answers.

  • Is intNumber greater than 49?

  • Is intNumber less than 49?

  • Is intNumber greater than or equal to 49?

  • Is intNumber less than or equal to 49?

  • Is strName not equal to Ben?

When working with string values, most of the time you’ll use the Equal To or Not Equal To operator. When working with numeric values (both integer and floating-point), you can use all of these arithmetic operators discussed in the previous chapter.

Using Not Equal To

You have not used Not Equal To yet, so test the Not Equal To operator with strings.

The Not Equal To operator will be false when Equal To is true and it will be true when Equal To is false. Let’s try this out.

  1. Create a Windows Forms Application project called If Demo. Add a TextBox control and a Button control. Set the Name property for TextBox1 to txtName and the Text property to Stephanie. Set the Name property for Button1 to btnCheck and the Text property to Check.

  2. Double-click the Button control to create its Click event handler. Add the bolded code:

    Private Sub btnCheck_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles btnCheck.Click
    
        ‘Declare a variable and get the name from the text box
        Dim strName As String
        strName = txtName.Text
    
        ‘Is the name Wendy?
        If strName <> ″Wendy″ Then
            MessageBox.Show(″The name is *not* Wendy.″, ″If Demo″)
        End If
    End Sub
    
  3. Save your project and then run it. When the form is displayed, click the Check button and you will see a message box indicating that the name is not Wendy.

The Not Equal To operator looks like this: <>. When the button is clicked, the first thing you do is retrieve the name from the text box by looking at its Text property:

‘Declare a variable and get the name from the text box
Dim strName As String
strName = txtName.Text

Note

After you have the name, you use an If statement. This time, however, you use the Not Equal To operator, rather than the Equal To operator. Also note that you are comparing two string values:

‘Is the name Wendy?
If strName <> ″Wendy″ Then
    MessageBox.Show(″The name is *not* Wendy.″, ″If Demo″)
End If

The code between Then and End If executes only if the answer to the question asked in the If statement is True. You may find this to be a bit of a heady principle, because the question you’re asking is, "Is strName not equal to Wendy?" to which the answer is "Yes, the strName is not equal to Wendy." Because the answer to this question is yes, or True, the code runs and the message box displays. However, if you enter Wendy into the text box and click Check, nothing happens, because the answer to the question is "No, the strName is equal to Wendy"; therefore, you have a no, or False, answer.

Note

If you try this, be sure to enter Wendy with an uppercase W and the rest of the letters in lowercase; otherwise, the application won’t work properly. You’ll see why later.

An alternative way of checking that something does not equal something else is to use the Not keyword. The condition in the If statement could have been written as follows:

If Not strName = ″Wendy″ Then

Using the Numeric Operators

In this section, you take a look at the four other comparison operators you can use. These are all fairly basic, so you’ll go through this quite fast.

In this try it out, you will work with greater than, less than, greater than or equal to, and less than or equal to.

  1. Return to the Forms Designer for the If Demo project. Add another TextBox control and set its Name property to txtValue. Add another Button control and set its Name property to btnCheckNumbers and its Text property to Check Numbers.

  2. Double-click the Check Numbers button and add the following bolded code to its Click event handler:

    Private Sub btnCheckNumbers_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles btnCheckNumbers.Click
    
        ‘Declare variable
        Dim intNumber As Integer
    
        Try
            ‘Get the number from the text box
            intNumber = CType(txtValue.Text, Integer)
        Catch
            Exit Sub
        End Try
    
        ‘Is intNumber less than 27?
        If intNumber < 27 Then
            MessageBox.Show(″Is ‘intNumber' less than 27? Yes!″, ″If Demo″)
        Else
            MessageBox.Show(″Is ‘intNumber' less than 27? No!″, ″If Demo″)
        End If
    End Sub
    
  3. Run the project. Enter 14 into the text box and click the Check Numbers button. You’ll be told whether the number entered is less than or greater than 27, as shown in Figure 4-4.

    Menu

    FIGURE 4-4

First, you get the value back from the text box. However, there is a slight wrinkle. Because this is a text box, end users are free to enter anything they like into it, and if a series of characters that cannot be converted into an integer is entered, the program will crash. Therefore, you add an exception handler to ensure that you always get a value back. Also, with the Option Strict option turned on, you’ll need to convert the string value in the text box to an Integer data type using the CType function as you did in the last chapter. If the user enters something invalid, intNumber remains 0 (the default value); otherwise, it will be whatever is entered:

‘Declare variable
Dim intNumber As Integer

Try
    ‘Get the number from the text box
    intNumber = CType(txtValue.Text, Integer)
Catch
End Try

Note

You’ll be introduced to exception handling properly in Chapter 10. For now, you can safely ignore it!

The Less Than operator looks like this: <. Here, you test to determine whether the number entered was less than 27, and if it is, you say so in a message box; otherwise, you say No:

‘Is intNumber less than 27?
If intNumber < 27 Then
    MessageBox.Show(″Is ‘intNumber' less than 27? Yes!″, ″If Demo″)
Else
    MessageBox.Show(″Is ‘intNumber' less than 27? No!″, ″If Demo″)
End If

Here’s something interesting, though. If you actually enter 27 into the text box and click the button, you’ll see a message box that tells you intNumber is not less than 27. The If statement said No, and it’s right; intNumber is actually equal to 27, and the cutoff point for this operator is anything up to but not including the value itself. You can get around this problem with a different operator, as you’ll see in the next Try It Out.

The Less Than Or Equal To operator will be true when the tested value is less than the comparison value and also when the two values are equal. You will see this next.

  1. Return to the Code Editor and change the If statement in the btnCheckNumbers_Click event handler as shown here:

    Try
        ‘Get the number from the text box
        intNumber = CType(txtValue.Text, Integer)
    Catch
        Exit Sub
    End Try
    
     ‘Is intNumber less than or equal to 27?
    If intNumber <= 27 Then
        MessageBox.Show(″Is ‘intNumber' less than or equal to 27? Yes!″, _
            ″If Demo″)
    Else
        MessageBox.Show(″Is ‘intNumber' less than or equal to 27? No!″, _
            ″If Demo″)
    End If
    
  2. Now run the project and enter 27 into the text box. Click the Check Numbers button and you should see the results shown in Figure 4-5.

    Is intNumber less than or equal to 27? Yes!

    FIGURE 4-5

Tip

In this example, the Less Than Or Equal To operator looks like this: <=. In this situation, you’re extending the possible range of values up to and including the value you’re checking. Therefore, in this case when you enter 27, you get the answer Yes, n is less than or equal to 27. This type of operator is known as an inclusive operator.

The final two operators look very similar to this, so let’s look at them now.

In this example, you see how to use the Greater Than and Greater Than Or Equal To Operators.

  1. Return to the Code Editor and add two additional If statements in the btnCheckNumbers_Click event handler, as shown here:

        ‘Is intNumber less than or equal to 27?
        If intNumber <= 27 Then
            MessageBox.Show(″Is ‘intNumber' less than or equal to 27? Yes!″, _
                ″If Demo″)
        Else
            MessageBox.Show(″Is ‘intNumber' less than or equal to 27? No!″, _
                ″If Demo″)
        End If
    
         ‘Is intNumber greater than 27?
        If intNumber > 27 Then
            MessageBox.Show(″Is ‘intNumber' greater than 27? Yes!″, _
                ″If Demo″)
        Else
            MessageBox.Show(″Is ‘intNumber' greater than 27? No!″, _
                ″If Demo″)
        End If
    
        ‘Is intNumber greater than or equal to 27?
        If intNumber >= 27 Then
            MessageBox.Show(″Is ‘intNumber' greater than or equal to 27? Yes!″, _
                ″If Demo″)
        Else
            MessageBox.Show(″Is ‘intNumber' greater than or equal to 27? No!″, _
                ″If Demo″)
        End If
    End Sub
    
  2. Run the program. This time enter a value of 99 and click the Check Numbers button. You’ll see three message boxes, one after the other. The first message box will indicate that intNumber is not less than or equal to 27, while the second message box will indicate that intNumber is greater than 27. The final message box will indicate that intNumber is greater than or equal to 27.

Tip

The Greater Than and Greater Than Or Equal To operators are basically the opposite of their Less Than counterparts. This time, you’re asking, "Is intNumber greater than 27?" and, "Is intNumber greater than or equal to 27?" The results speak for themselves.

The And and Or Operators

What happens when you need your If statement to test more than one condition? For example, suppose you want to ensure that intNumber is less than 27 and greater than 10. Or, how about checking that strName is "Wendy" or "Stephanie"? You can combine operators used with an If statement with the And and Or operators, as you do in the next Try It Out.

Tip

Code file And Or Demo.zip available for download atCreate a new Windows Forms Application called And Or Demo.

  1. Create a new Windows Forms Application called And Or Demo.

  2. In the Forms Designer for Form1, add two TextBox controls and a Button control. Set the Name properties of the text boxes to txtName1 and txtName2 and the Name property of the button to btnOrCheck.

  3. Set the Text property for txtName1 to Wendy and the Text property for txtName2 to Stephanie. Finally, set the Text property for btnOrCheck to Or Check. Your completed form should look similar to the one shown in Figure 4-6.

    New Project

    FIGURE 4-6

  4. Double-click the Or Check button and add the following code to its Click event handler:

    Private Sub btnOrCheck_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles btnOrCheck.Click
    
        ‘Declare variables
        Dim strName1 As String, strName2 As String
    
        ‘Get the names
        strName1 = txtName1.Text
        strName2 = txtName2.Text
    
        ‘Is one of the names Wendy?
        If strName1 = ″Wendy″ Or strName2 = ″Wendy″ Then
            MessageBox.Show(″One of the names is Wendy.″, _
                ″And Or Demo″)
        Else
            MessageBox.Show(″Neither of the names is Wendy.″, _
                ″And Or Demo″)
        End If
    End Sub
    
  5. Run the project and click the button. You should see the results shown in Figure 4-7.

    New Project

    FIGURE 4-7

  6. Click OK to dismiss the message box dialog and flip the names around so that the top one (txtName1) is Stephanie and the bottom one (txtName2) is Wendy. Click the button again. You’ll see a message box indicating that one of the names is Wendy.

  7. Click OK to dismiss the message box again and this time change the names so that neither of them is Wendy. Click the button and you should see a message box indicating that neither of the names is Wendy.

This example shows that the Or operator is a great way of building If statements that compare two different values in a single hit. In your Click event handler, you first declare your variables and then retrieve both names and store them in variables strName1 and strName2:

‘Declare variables
Dim strName1 As String, strName2 As String

‘Get the names
strName1 = txtName1.Text
strName2 = txtName2.Text

Notice that you’ve defined two variables on the same line. This is a perfectly legitimate coding practice, although it can sometimes make the code look congested. The variables are separated with commas; note that it’s still important to use the As keyword to tell Visual Basic 2010 the data type of each variable.

Once you have both names, you use the Or operator to combine two separate If statements. The question you’re asking here is, "Is strName1 equal to Wendy or is strName2 equal to Wendy?" The answer to this question (provided that one of the text boxes contains the name Wendy) is, "Yes, either strName1 is equal to Wendy or strName2 is equal to Wendy." Again, it’s a yes/no or true/ false answer, even though the question is seemingly more complex:

‘Is one of the names Wendy?
If strName1 = ″Wendy″ Or strName2 = ″Wendy″ Then
    MessageBox.Show(″One of the names is Wendy.″, _
        ″And Or Demo″)
Else
    MessageBox.Show(″Neither of the names is Wendy.″, _
        ″And Or Demo″)
End If

Using the And Operator

The And operator is conceptually similar to Or, except that both parts of the condition need to be satisfied, as you will see in the next Try It Out.

Tip

Code file And Or Demo.zip available for download at Wrox.com

Let’s see how to use the And operator.

  1. Return to the Forms Designer in the And Or Demo project. Add another Button control to the form. Set its Name property to btnAndCheck and its Text property to And Check. Double-click the button and add the following bolded code to its Click event handler:

    Private Sub btnAndCheck_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles btnAndCheck.Click
    
        ‘Declare variables
        Dim strName1 As String, strName2 As String
    
        ‘Get the names
        strName1 = txtName1.Text
        strName2 = txtName2.Text
    
        ‘Are both names Wendy?
        If strName1 = ″Wendy″ And strName2 = ″Wendy″ Then
            MessageBox.Show(″Both names are Wendy.″, _
                ″And Or Demo″)
        Else
            MessageBox.Show(″One of the names is not Wendy.″, _
                ″And Or Demo″)
        End If
    End Sub
    
  2. Run the program and click the And Check button. A message box will tell you that one of the names is not Wendy.

  3. Change both names so that they are both Wendy and click the button. You’ll see the results shown in Figure 4-8.

And Or Demo

FIGURE 4-8

Let’s review why this works. After you retrieve both names from the text boxes, you compare them. In this case, you’re asking the question, "Is strName1 equal to Wendy and is strName2 equal to Wendy?" In this case, both parts of the If statement must be satisfied in order for the "Both names are Wendy" message box to be displayed:

        ‘Are both names Wendy?
        If strName1 = ″Wendy″ And strName2 = ″Wendy″ Then
            MessageBox.Show(″Both names are Wendy.″, _
                ″And Or Demo″)
        Else
            MessageBox.Show(″One of the names is not
               Wendy.″, _
                ″And Or Demo″)
        End If

More on And and Or

You’ve seen And and Or used with strings. They can also be used with numeric values, like this:

If intX = 2 And intY = 3 Then
    MessageBox.Show(″Hello, both of the conditions have been satisfied!″)
End If

or

If intX = 2 Or intY = 3 Then
    MessageBox.Show(″Hello, one of the conditions has been satisfied!″)
End If

In Visual Basic 2010, there’s no realistic limit to the number of And operators or Or operators that you can include in a statement. It’s perfectly possible to do the following, although it’s unlikely you’d want to do so:

If intA = 1 And intB = 2 And intC = 3 And intD = 4 And intE = 5 And _
    intF = 6 And intG = 7 And intH = 1 And intI = 2 And intJ = 3 And _
    intK = 4 And intL = 5 And intM = 6 And intN = 7 And intO = 1 And _
    intP = 2 And intQ = 3 And intR = 4 And intS = 5 And intT = 6 And _
    intU = 7 And intV = 1 And intW = 2 And intX = 3 And intY = 4 And _
    intZ = 5 Then
    MessageBox.Show(″That's quite an If statement!″)
End If

Finally, it’s possible to use parentheses to group operators and look for a value within a range. For example, say you want to determine whether the value of intX is between 12 and 20 exclusive or between 22 and 25 exclusive. You can use the following If…Then statement:

If (intX > 12 And intX < 20) Or (intX > 22 And intX < 25) Then

There are many other combinations of operators, far more than we have room to go into here. Rest assured that if you want to check for a condition, there is a combination to suit your needs.

String Comparison

When working with strings and If statements, you often run into the problem of uppercase and lowercase letters. A computer treats the characters A and a as separate entities, even though people consider them to be similar. This is known as case sensitivity—meaning that the case of the letters does matter when comparing strings. For example, if you run the following code, the message box would not be displayed:

Dim strName As String
strName = ″Winston″
If strName = ″WINSTON″ Then
    MessageBox.Show(″Aha! You are Winston.″)
End If

Because WINSTON is not, strictly speaking, the same as Winston, this If statement will not return a message. However, in many cases you don’t actually care about case, so you have to find a way of comparing strings and ignoring the case of the characters.

In this Try It Out, you work with case-insensitive strings.

  1. Return to the Forms Designer in the And Or Demo project and add another TextBox and Button control to the form.

  2. Set the Name property of the TextBox to txtName3 and the Text property to Bryan. Set the Name property of the Button to btnStringCompare and the Text property to String Compare.

  3. Double-click the String Compare button to open its Click event handler and add the following bolded code:

    Private Sub btnStringCompare_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles btnStringCompare.Click
    
        ‘Declare variable
        Dim strName As String
    
        ‘Get the name
        strName = txtName3.Text
    
        ‘Compare the name
        If String.Compare(strName, ″BRYAN″, True) = 0 Then
            MessageBox.Show(″Hello, Bryan!″, ″And Or Demo″)
        End If
    End Sub
    
  4. Run the project and click the button. You should see results like the ones shown in Figure 4-9.

    And Or Demo - Hello, Bryan!

    FIGURE 4-9

  5. Dismiss the message box and enter the name in the last text box as BrYaN, or some other combination of uppercase and lowercase letters, and click the button. You should still see a message box that says "Hello, Bryan!"

  6. However, if you enter a name that isn’t Bryan, the message box will not be displayed when you click the button.

After you get the name back from the text box, you have to use a function to compare the two values, rather than use the basic Equal To operator. In this instance, you’re using the Compare method on System.String, passing it the two strings you want to compare. The first string is the value stored in strName (which is the value entered into the text box), with the second string being "BRYAN". The last parameter that you supply is True, which tells Compare to perform a case-insensitive match; in other words, it should ignore the differences in case. If you supplied False for this parameter, the comparison would be case sensitive, in which case you would be no better off than using the vanilla Equal To operator:

‘Compare the name
If String.Compare(strName, ″BRYAN″, True) = 0 Then
    MessageBox.Show(″Hello, Bryan!″, ″And Or Demo″)
End If

Warning

String.Compare returns a fairly curious result. It actually returns an integer, rather than a True or False value. This is because String.Compare can be used to determine how two strings differ, rather than just a straightforward, "Yes, they are," or "No, they’re not." If the method returns 0, the strings match. If the method returns a value that is not 0, the strings do not match.

Note

String.Compare returns an indication of how different two strings are in order to help you build sorting algorithms.

Select Case

On occasion, you need to make a set of similar decisions such as this:

  • Is the customer called Bryan? If so, do this.

  • Is the customer called Stephanie? If so, do this.

  • Is the customer called Cathy? If so, do this.

  • Is the customer called Betty? If so, do this.

  • Is the customer called Edward? If so, do this.

You can obviously do this with a set of If…Then statements. In fact, it would look a little like this:

If Customer.Name = ″Bryan″ Then
(do something)
ElseIf Customer.Name = ″Stephanie″ Then
(do something)
ElseIf Customer.Name = ″Cathy″ Then
(do something)
ElseIf Customer.Name = ″Betty″ Then
(do something)
ElseIf Customer.Name = ″Edward″ Then
(do something)
End If

What happens if you decide you want to check Customer.FirstName instead of Customer.Name? You’d have to change every If statement, which is a pain. In addition, if Customer.Name turns out to be "Edward", you still have to go through the other four If statements, which is very inefficient. In the next Try It Out, you learn a better way.

  1. Create a new Windows Forms Application project. Call it Select Demo. Set the Text property of the form to Select Case.

  2. From the Toolbox, add a ListBox control to the form and set its Name property to lstData, its Dock property to Fill, and its IntegralHeight property to False.

  3. With lstData selected in the Forms Designer, look at the Properties window and select the Items property. Click the ellipses button to the right of the property, and in the String Collection Editor that appears, add the five names on separate lines as shown in Figure 4-10.

    String Collection Editor

    FIGURE 4-10

  4. Click OK to save the changes. The names will be added to your list box.

  5. Now double-click lstData to create a new SelectedIndexChanged event handler and add the following bolded code:

    Private Sub lstData_SelectedIndexChanged(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles lstData.SelectedIndexChanged
    
        ‘Declare variables
        Dim strName As String
        Dim strFavoriteColor As String
    
        ‘Get the selected name
        strName = lstData.Items(lstData.SelectedIndex).ToString
    
        ‘Use a Select Case statement to get the favorite color
        ‘of the selected name
        Select Case strName
            Case ″Bryan″
                strFavoriteColor = ″Madras Yellow″
    
            Case ″Ashley″
                strFavoriteColor = ″Sea Blue″
    
            Case ″Jennifer″
                strFavoriteColor = ″Morning Mist″
    
            Case ″Eddie″
                strFavoriteColor = ″Passionate Purple″
    
            Case ″Katelyn″
                strFavoriteColor = ″Red″
        End Select
    
        ‘Display the favorite color of the selected name
        MessageBox.Show(strName & ″'s favorite color is ″ & _
            strFavoriteColor, ″Select Demo″)
    End Sub
    
  6. Save your project and then run it. Whenever you click one of the names, a message box like the one shown in Figure 4-11 will appear.

    Select Demo - Katelyn's favorite color is Red

    FIGURE 4-11

In this Try It Out, the first thing you need to do in the SelectedIndexChanged event handler is declare your variables and determine which name was selected. You do this by finding the item in the list that matches the current value of the SelectedIndex property. The Items collection of the ListBox class returns an Object data type, so you use the ToString method to convert the object to a String data type for the strName variable:

‘Declare variables
Dim strName As String
Dim strFavoriteColor As String

‘Get the selected name
strName = lstData.Items(lstData.SelectedIndex).ToString

When you have that, you start a Select Case…End Select block. To do this, you need to supply the variable that you’re matching against; in this case, you’re using the name that was selected in the list.

Inside the Select Case…End Select block, you define separate Case statements for each condition to be checked against. In this example, you have five, and each is set to respond to a different name. If a match can be found, Visual Basic 2010 executes the code immediately following the relevant Case statement.

For example, if you clicked Katelyn, the message box would display Red as her favorite color, because Visual Basic 2010 would execute the line, strFavoriteColor = "Red". If you clicked Ashley, the message box would display Sea Blue as her favorite color, because Visual Basic 2010 would execute strFavoriteColor = "Sea Blue".

‘Use a Select Case statement to get the favorite color
‘of the selected name
Select Case strName
    Case ″Bryan″
        strFavoriteColor = ″Madras Yellow″

    Case ″Ashley″
        strFavoriteColor = ″Sea Blue″

    Case ″Jennifer″
        strFavoriteColor = ″Morning Mist″

    Case ″Eddie″
        strFavoriteColor = ″Passionate Purple″

    Case ″Katelyn″
        strFavoriteColor = ″Red″
End Select

Note

After the Select Case…End Select block, you display a message box:

‘Display the favorite color of the selected name
MessageBox.Show(strName & ″'s favorite color is ″ & _
    strFavoriteColor, ″Select Demo″)

Tip

How do you get out of a Select Case…End Select block? As you’re processing code that’s beneath a Case statement, if you meet another Case statement, Visual Basic 2010 jumps out of the block and down to the line immediately following the block. Here’s an illustration:

  1. The user clicks Katelyn. The SelectedIndexChanged event is activated, and you store "Katelyn" in strName.

  2. You reach the Select Case statement. This is set to compare the value in strName with one of the five supplied names.

  3. Visual Basic 2010 finds a Case statement that satisfies the request and immediately moves to strFavoriteColor = "Red".

  4. Visual Basic 2010 moves to the next line. This is another Case statement, and, seeing that you’re already in one, you move to the first line after the Select Case…End Select block and display the message box.

Select Case is a powerful and easy-to-use technique for making a choice from several options. However, you must leave the block as soon as another Case statement is reached.

Case-Insensitive Select Case

Just like If, Select Case is case sensitive; prove it in the next Try It Out.

In this Try It Out, you will prove that case matters when using Select Case to compare strings.

  1. Return to the Select Demo project and open the Forms Designer. Locate the Items property for the list box and open the String Collection Editor again.

  2. Change all the names so that they appear in all uppercase letters, as shown in Figure 4-12.

    String Collection Editor

    FIGURE 4-12

  3. Click OK to save your changes and then run the project. You’ll notice that when you click a name, the message box doesn’t specify a favorite color, as shown in Figure 4-13.

    Select Demo - ASHLEY's favorite color is

    FIGURE 4-13

Select Case performs a case-sensitive match, just like If. This means that if you provide the name BRYAN or EDDIE to the statement, there won’t be a corresponding Case statement because you’re trying to say:

If ″EDDIE″ = ″Eddie″

or

If ″BRYAN″ = ″Bryan″

Earlier in this chapter, you learned how to use the String.Compare method to perform case-insensitive comparisons with If statements. With Select Case, you can’t use this method, so if you want to be insensitive towards case, you need to employ a different technique—the one you learn in the next Try It Out.

In this example, you will learn another way to compare strings using Select Case.

  1. Return to the Select Demo project, open the Code Editor for Form1, and make the following changes to the event handler for SelectedIndexChanged. Pay special attention to the Case statements—the name that you’re trying to match must be supplied in all lowercase letters:

    Private Sub lstData_SelectedIndexChanged(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles lstData.SelectedIndexChanged
    
        ‘Declare variables
        Dim strName As String
        Dim strFavoriteColor As String
    
        ‘Get the selected name
        strName = lstData.Items(lstData.SelectedIndex).ToString
    
        ‘Use a Select Case statement to get the favorite color
        ‘of the selected name
        Select Case strName.ToLower
            Case ″bryan″
                strFavoriteColor = ″Madras Yellow″
    
            Case ″ashley″
                strFavoriteColor = ″Sea Blue″
    
            Case ″jennifer″
                strFavoriteColor = ″Morning Mist″
    
            Case ″eddie″
                strFavoriteColor = ″Passionate Purple″
    
            Case ″katelyn″
                strFavoriteColor = ″Red″
        End Select
    
        ‘Display the favorite color of the selected name
        MessageBox.Show(strName & ″'s favorite color is ″ & strFavoriteColor, _
            ″Select Demo″)
    End Sub
    
  2. Run the project and try selecting a name again. This time you will see that the message box includes the favorite color of the person you clicked, as shown in Figure 4-14.

    Select Demo - KATELYN's favorite color is Red

    FIGURE 4-14

To make the selection case insensitive in this example, you have to convert the strName variable into all lowercase letters. This is done using the ToLower method:

Select Case strName.ToLower

This means that whatever string you’re given (whether it’s "BRYAN" or "Bryan"), you always convert it to all lowercase ("bryan"). However, when you do this, you have to ensure that you’re comparing apples to apples (and not to Apples), which is why you had to convert the values you’re checking against in the Case statements to all lowercase too. Therefore, when given "BRYAN", you convert this to "bryan", and then try to find the Case that matches "bryan":

    Case ″bryan″
        strFavoriteColor = ″Madras Yellow″

    Case ″ashley″
        strFavoriteColor = ″Sea Blue″

    Case ″jennifer″
        strFavoriteColor = ″Morning Mist″

    Case ″eddie″
        strFavoriteColor = ″Passionate Purple″

    Case ″katelyn″
        strFavoriteColor = ″Red″
End Select

Finally, once you have the favorite color, you display a message box as usual.

Note

You could have done the opposite of this and converted all the names to uppercase and used strName.ToUpper instead of strName.ToLower.

Multiple Selections

You’re not limited to matching one value inside a Select Case … End Select block. You can also match multiple items.

In this Try It Out, you’ll modify the application so that you also report the sex of whoever you click on.

  1. Return to the Select Demo project, open the Code Editor for Form1, and add the bolded code in the SelectedIndexChanged handler:

       ‘Display the favorite color of the selected name
       MessageBox.Show(strName & ″'s favorite color is ″ & strFavoriteColor, _
           ″Select Demo″)
    
       ‘Use a Select Case statement to display a person's gender
       Select Case strName.ToLower
           Case ″bryan″, ″eddie″, ″ashley″
               MessageBox.Show(″This person's gender is male.″, ″Select Demo″)
           Case ″jennifer″, ″katelyn″
               MessageBox.Show(″This person's gender is female.″, ″Select Demo″)
       End Select
    End Sub
    
  2. Run the project and click one of the female names. You will see results as shown in Figure 4-15, following the message box indicating the person’s favorite color.

    Select Demo - This person's gender is female.

    FIGURE 4-15

OK, now let’s look at how multiple selections work. The code you use to get back the name and initialize the Select Case block remains the same. However, in each Case statement you can provide a list of possible values, separated with commas. In the first one, you look for bryan or edward or ashley. If any of these matches, you run the code under the Case statement:

Case ″bryan″, ″eddie″, ″ashley″
    MessageBox.Show(″This person's gender is male.″, ″Select Demo″)

In the second statement, you look for jennifer or katelyn. If any of these two matches, you again run the code under the Case statement:

Case ″jennifer″, ″katelyn″
    MessageBox.Show(″This person's gender is female.″, ″Select Demo″)

It’s important to realize that these are all or matches. You’re saying "one or the other," not "one and the other."

The Case Else Statement

What happens if none of the Case statements that you’ve included is matched? You saw this before in the demonstration of the case-sensitive nature of Select Case. In the next Try It Out, you see it with the Case Else statement.

  1. Return to the Forms Designer, locate the Items property for the list box, and open the String Collection Editor again. Add another name in all uppercase letters to the collection and then click the OK button.

  2. In the lstData_SelectedIndexChanged event handler, add the following bolded code:

        ‘Use a Select Case statement to display a person's gender
        Select Case strName.ToLower
            Case ″bryan″, ″edward″
                MessageBox.Show(″This person's gender is male.″, ″Select Demo″)
            Case ″stephanie″, ″cathy″, ″betty″
                MessageBox.Show(″This person's gender is female.″, ″Select Demo″)
            Case Else
                MessageBox.Show(″I don't know this person's gender.″, _
                    ″Select Demo″)
        End Select
    End Sub
    
  3. Run the project and click the last name that you just added. You will see results similar to those shown in Figure 4-16.

    Select Demo - I don't know this person's gender.

    FIGURE 4-16

The Case Else statement is used if none of the other supplied Case statements match what you’re looking for. There isn’t a Case "tony" defined within the block, so you default to using whatever is underneath the Case Else statement. In this instance, you display a message box indicating that you do not know the gender of the person who’s been selected.

Different Data Types with Select Case

In this chapter, you used Select Case with variables of type String. However, you can use Select Case with all basic data types in Visual Basic 2010, such as Integer, Double, and Boolean.

In day-to-day work, the most common types of Select Case are based on String and Integer data types. However, as a general rule, if a data type can be used in an If statement with the Equals (=) operator, it will work with Select Case.

Loops

When writing computer software, you often need to perform the same task several times to get the effect you want. For example, you might need to create a telephone bill for all customers, or read in 10 files from your computer’s disk.

To accomplish this, you use a loop, and in this section you’ll take a look at the two main types of loops available in Visual Basic 2010:

  • For loops: These loops occur a certain number of times (for example, exactly 10 times).

  • Do loops: These loops keep running until a certain condition is reached (for example, until all of the data is processed).

The For…Next Loop

The simplest loop to understand is the For…Next loop.

You will learn to build a For…Next Loop in this Try It Out.

  1. Create a new Windows Forms Application project called Loops.

  2. Add a ListBox and a Button control to the form.

  3. Change the Name property of the list box to lstData and its IntegralHeight property to False.

  4. Change the Name property of the button to btnForNextLoop. Set its Text property to For Next Loop. You’ll be adding more buttons later so make this button a little wider, as shown in Figure 4-17.

    Form1

    FIGURE 4-17

  5. Double-click the button to create its Click event handler and add the following bolded code:

    Private Sub btnForNextLoop_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles btnForNextLoop.Click
    
        ‘Declare variable
        Dim intCount As Integer
    
        ‘Clear the list
        ClearList()
    
        ‘Perform a loop
        For intCount = 1 To 5
            ‘Add the item to the list
            lstData.Items.Add(″I'm item ″ & intCount.ToString & _
                ″ in the list!″)
        Next
    End Sub
    
  6. Now create the following method:

    Private Sub ClearList()
        ‘Clear the list
        lstData.Items.Clear()
    End Sub
    
  7. Save and run the project and then click the For Next Loop button. You should see results like those in Figure 4-18.

    Form1

    FIGURE 4-18

First, inside the Click event handler, you define a variable:

‘Declare variable
Dim intCount As Integer

Next, you clear the list box by calling the ClearList method. Although the list is empty at this point, you’ll be adding more buttons to this project in the following Try It Out exercises, and may want to compare the results of the each of the buttons.

‘Clear the list
ClearList()

Then you start the loop by using the For keyword. This tells Visual Basic 2010 that you want to create a loop. Everything that follows the For keyword is used to define how the loop should act. In this case, you’re giving it the variable you just created and then telling it to count from 1 to 5:

‘Perform a loop
For intCount = 1 To 5

The variable that you give the loop (in this case, intCount) is known as the control variable. When you first enter the loop, Visual Basic 2010 sets the control variable to the initial count value—in this case, 1. After the loop starts, Visual Basic 2010 moves to the first line within the For loop—in this case, the line that adds a string to the list box:

‘Add the item to the list
lstData.Items.Add(″I'm item ″ & intCount.ToString & _
    ″ in the list!″)

This time, this line of code adds I’m item 1 in the list! to the list box. Visual Basic 2010 then hits the Next statement, and that’s where things start to get interesting:

Next

When the Next statement is executed, Visual Basic 2010 increments the control variable by one. The first time Next is executed, the value in intCount changes from 1 to 2. Providing that the value of the control variable is less than or equal to the "stop" value (in this case, 5), Visual Basic 2010 moves back to the first line after the For statement, in this case:

‘Add the item to the list
lstData.Items.Add(″I'm item ″ & intCount.ToString & _
    ″ in the list!″)

This time, this line of code adds I’m item 2 in the list! to the list box. Again, after this line is executed, you run the Next statement. The value of intCount is now incremented from 2 to 3, and because 3 is less than or equal to 5, you move back to the line that adds the item to the list. This happens until intCount is incremented from 5 to 6. Because 6 is greater than the stop value for the loop, the loop stops.

Note

When you’re talking about loops, you tend to use the term iteration. One iteration includes one movement from the For statement to the Next statement. Your loop has five iterations.

The method you define contains only one line of code but its reuse becomes apparent in the next Try It Out. This method merely clears the Items collection of the list box:

Private Sub ClearList()
    ‘Clear the list
    lstData.Items.Clear()
End Sub

Using the Step Keyword

You don’t have to start your loop at 1—you can pick any value you like. Nor do you have to increment the control value by 1 on each iteration—again, you can increment by any value you like.

In this Try It Out, you learn about the flexibility of the Step keyword.

  1. Return to the Forms Designer for the Loops project. Add a Button control to your form. Set its Name property to btnForNextLoopWithStep and its Text property to For Next Loop w/Step.

  2. Double-click the button and add the following bolded code in the Click event handler:

    Private Sub btnForNextLoopWithStep_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles btnForNextLoopWithStep.Click
    
        ‘Clear the list
        ClearList()
    
        ‘Perform a loop
        For intCount As Integer = 4 To 62 Step 7
            ‘Add the item to the list
            lstData.Items.Add(intCount.ToString)
        Next
    End Sub
    
  3. Run the project and click the For Next Loop w/Step button. You will see results like those in Figure 4-19.

    Form1

    FIGURE 4-19

The magic in this example all happens with this statement:

‘Perform a loop
For intCount As Integer = 4 To 62 Step 7

First, note that you didn’t declare the intCount variable using a Dim statement. This has been done as part of the For statement and makes this variable local to this loop. Using the As keyword and the data type for the variable (in this case, Integer), you have effectively declared an inline variable.

Next, instead of using 1 as the start value, you’re using 4. This means that on the first iteration of the loop, intCount is set to 4, which you can see because the first item added to the list is indeed 4. You’ve used the Step keyword to tell the loop to increment the control value by 7 on each iteration, rather than by the default of 1. This is why, by the time you start running the second iteration of the loop, intCount is set to 11, not 5.

Although you gave For a stop value of 62, the loop has actually stopped at 60 because the stop value is a maximum. After the ninth iteration, intCount is actually 67, which is more than 62, so the loop stops.

Looping Backwards

By using a Step value that’s less than 0 (or a negative number), you can make the loop go backward, rather than forward, as demonstrated in the next Try It Out.

In this example, you will make a loop go backwards.

  1. Return to the Forms Designer and add another Button control to your form, setting its Name property to btnBackwardsForNextLoop and its Text property to Backwards For Next Loop.

  2. Double-click the button and add the following bolded code in the Click event handler:

    Private Sub btnBackwardsForNextLoop_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles btnBackwardsForNextLoop.Click
    
        ‘Clear the list
        ClearList()
    
        ‘Perform a loop
        For intCount As Integer = 10 To 1 Step -1
            ‘Add the item to the list
            lstData.Items.Add(intCount.ToString)
        Next
    End Sub
    
  3. Run the project and click the Backwards for Next Loop button. You should see results like those shown in Figure 4-20.

    Form1

    FIGURE 4-20

Let’s review. If you use a negative number, like -1, For tries to add -1 to the current control value. Adding a negative number has the effect of subtracting the number, so intCount goes from its start value of 10 to its new value of 9, and so on until the stop value is reached.

The For Each…Next Loop

In practical, day-to-day work, it’s unlikely that you’ll use For…Next loops as illustrated here. Because of way the .NET Framework typically works, you’ll usually use a derivative of the For…Next loop called the For Each … Next loop.

In the algorithms you design, whenever a loop is necessary, you’ll have a collection of things to work through, and usually this set is expressed as an array. For example, you might want to look through all of the files in a folder, looking for those that are larger than a particular size. When you ask the .NET Framework for a list of files, you are returned an array of strings, with each string in that array describing a single file.

In this Try It Out, you’ll modify your Loops application so that it returns a list of folders contained at the root of your C drive.

  1. Return to the Forms Designer, add another Button control to your form, and set its Name property to btnForEachLoop and its Text property to For Each Loop.

  2. Double-click the button and add the following bolded code to the Click event handler:

    Private Sub btnForEachLoop_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles btnForEachLoop.Click
    
        ‘Clear the list
        ClearList()
    
        ‘List each folder at the root of your C drive
        For Each strFolder As String In _
            My.Computer.FileSystem.GetDirectories(″C:\″)
    
            ‘Add the item to the list
            lstData.Items.Add(strFolder)
        Next
    End Sub
    
  3. Run the project and click the For Each Loop button. You should see a list of folders that are at the root of your C drive.

In the For Each Loop example, the My namespace in the .NET Framework exposes several classes that make it easy to find the information that you’ll use on a daily basis. In particular, the Computer class provides several other classes related to the computer on which your program is running. Since you want to find out about files and folders, you use the FileSystem class, which provides methods and properties for working with files and folders.

The GetDirectories method returns a collection of strings representing names of directories (or folders) on your computer. In this case, you use it to return a collection of folder names in the root of the computer’s C drive.

The concept with a For Each…Next loop is that for each iteration, you’ll be given the "thing" that you’re supposed to be working with. You need to provide a source of things (in this case, a collection of strings representing folder names) and a control variable into which the current thing can be put. The GetDirectories method provides the collection, and the inline variable strFolder provides the control variable:

‘List each folder at the root of your C drive
For Each strFolder As String In _
    My.Computer.FileSystem.GetDirectories(″C:\″)
Next

This means that on the first iteration, strFolder is equal to the first item in the string collection (in this case, "C:\$Recycle.Bin"). You then add that item to the list box:

‘Add the item to the list
lstData.Items.Add(strFolder)

As with normal For…Next loops, for every iteration of the loop, you’re given a string containing a folder name, and you add that string to the list. When there are no more folders to be returned, execution automatically drops out of the loop.

The Do…Loop Loops

The other kind of loop you can use is one that keeps happening until a certain condition is met. This is known as a Do…Loop, and there are a number of variations.

The first one you’ll learn about is the Do Until…Loop. This kind of loop keeps going until something happens.

For this Try It Out, you’re going to use the random number generator that’s built into the .NET Framework and create a loop that will keep generating random numbers until it produces the number 10. When you get the number 10, you’ll stop the loop.

  1. Return to the Forms Designer in the Loops project, add another Button control to your form, and set its Name property to btnDoUntilLoop and its Text property to Do Until Loop.

  2. Double-click the button and add the following bolded code to its Click event handler:

    Private Sub btnDoUntilLoop_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles btnDoUntilLoop.Click
    
        ‘Declare variables
        Dim objRandom As New Random
        Dim intRandomNumber As Integer = 0
    
        ‘Clear the list
        ClearList()
    
        ‘Process the loop until intRandomNumber = 10
        Do Until intRandomNumber = 10
            ‘Get a random number between 0 and 24
            intRandomNumber = objRandom.Next(25)
            ‘Add the number to the list
            lstData.Items.Add(intRandomNumber.ToString)
        Loop
    End Sub
    
  3. Run the project and click the Do Until Loop button. You’ll see results similar to the results shown in Figure 4-21. Keep clicking the button. The number of elements in the list is different each time.

    Form1

    FIGURE 4-21

A Do Until…Loop keeps running the loop until the given condition is met. When you use this type of loop, there isn’t a control variable per se; rather, you have to keep track of the current position of the loop yourself. You begin by declaring a variable (also known as an object) for the Random class, which provides methods for generating random numbers. This object has been prefixed with obj to specify that this is an object derived from a class. The next variable that you declare is the intRandomNumber, which is used to receive the random number generated by your objRandom object:

‘Declare variables
Dim objRandom As New Random()
Dim intRandomNumber As Integer = 0

Then you clear the list of any previous items that may have been added:

‘Clear the list
ClearList()

Next, you set up the loop, indicating that you want to keep running the loop until intRandomNumber is equal to 10:

‘Process the loop until intRandomNumber = 10
Do Until intRandomNumber = 10

With each iteration of the loop, you ask the random number generator for a new random number and store it in intRandomNumber. This is done by calling the Next method of objRandom to get a random number. In this case, you’ve passed 25 as a parameter to Next, meaning that any number returned should be between 0 and 24 inclusive—that is, the number you supply must be one larger than the biggest number you ever want to get. In other words, the bounds that you ask for are non-inclusive. You then add the number that you got to the list:

    ‘Get a random number between 0 and 24
    intRandomNumber = objRandom.Next(25)
    ‘Add the number to the list
    lstData.Items.Add(intRandomNumber.ToString)
Loop

The magic happens when you get to the Loop statement. At this point, Visual Basic 2010 returns not to the first line within the loop, but instead to the Do Until line. When execution returns to Do Until, the expression is evaluated. Provided it returns False, the execution pointer moves to the first line within the loop. However, if intRandomNumber is 10, the expression returns True, and instead of moving to the first line within the loop, you continue at the first line immediately after Loop. In effect, the loop is stopped.

Do While…Loop

The conceptual opposite of a Do Until…Loop is a Do While…Loop. This kind of loop keeps iterating while a particular condition is true. Let’s see it in action.

In this Try It Out, you will use a Do While…Loop to continue while a random number is less than 15.

  1. Return to the Forms Designer again and add another Button control to your form. Set its Name property to btnDoWhileLoop and its Text property to Do While Loop.

  2. Double-click the button and add the following bolded code to the Click event handler:

    Private Sub btnDoWhileLoop_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles btnDoWhileLoop.Click
    
        ‘Declare variables
        Dim objRandom As New Random
        Dim intRandomNumber As Integer = 0
    
        ‘Clear the list
        ClearList()
    
        ‘Process the loop while intRandomNumber < 15
        Do While intRandomNumber < 15
            ‘Get a random number between 0 and 24
            intRandomNumber = objRandom.Next(25)
            ‘Add the number to the list
            lstData.Items.Add(intRandomNumber.ToString)
        Loop
    End Sub
    
  3. Run the project and click the Do While Loop button. You’ll see something similar to the results shown in Figure 4-22.

    Form1

    FIGURE 4-22

Every time you press the button, the loop executes as long as the random number generator produces a number less than 15.

A Do While…Loop keeps running as long as the given expression remains True. As soon as the expression becomes False, the loop quits. When you start the loop, you check to ensure that intRandomNumber is less than 15. If it is, the expression returns True, and you can run the code within the loop:

‘Process the loop while intRandomNumber < 15
Do While intRandomNumber < 15
    ‘Get a random number between 0 and 24
    intRandomNumber = objRandom.Next(25)
    ‘Add the number to the list
    lstData.Items.Add(intRandomNumber.ToString)
Loop

Again, when you get to the Loop statement, Visual Basic 2010 moves back up to the Do While statement. When it gets there, it evaluates the expression again. If it’s True, you run the code inside the loop once more. If it’s False (because intRandomNumber is greater than or equal to 15), you continue with the first line after Loop, effectively quitting the loop.

Acceptable Expressions for a Do…Loop

You might be wondering what kind of expressions you can use with the two variations of Do…Loop. If you can use it with an If statement, then you can use it with a Do…Loop. For example, you can write this:

Do While intX > 10 And intX < 100

or

Do Until (intX > 10 And intX < 100) Or intY = True

or

Do While String.Compare(strA, strB) > 0

In short, it’s a pretty powerful loop!

Other Versions of the Do…Loop

It’s possible to put the Until or While statements after Loop, rather than after Do. Consider these two loops:

Do While intX < 3
     intX += 1
Loop

and

Do
    intX += 1
Loop While intX < 3

At first glance, it looks like the While intX < 3 has just been moved around. You might think that these two loops are equivalent—but there’s a subtle difference. Suppose the value of intX is greater than 3 (such as 4) when these two Do loops start. The first loop will not run at all. However, the second loop will run once. When the Loop While intX < 3 line is executed, the loop will be exited. This happens despite the condition saying that intX must be less than 3.

Now consider these two Do Until loops:

Do Until intX = 3
    intX += 1
Loop

and

Do
    intX += 1
Loop Until intX = 3

Again, although at first glance it looks like these two loops are equivalent, they’re not; and they behave slightly differently. Let’s say that intX is 3 this time. The first loop isn’t going to run, as intX already meets the exit condition for this loop. However, the second loop will run once. Then, when you execute Loop Until intX = 3 the first time, intX is now 4, so you go back to the start of the loop and increment intX to 5, and so on. In fact, this is a classic example of an infinite loop (discussed later in this chapter) and will not stop.

Note

When you use Loop While or Loop Until, you are saying that, no matter what, you want the loop to execute at least once. In general, it’s best to stick with Do While and Do Until, rather than use Loop While and Loop Until.

You may also come across a variation of Do While…Loop called While…End While. This convention is a throwback to previous versions of Visual Basic, but old-school developers may still use it with .NET code, so it’s important that you can recognize it. These two are equivalent, but you should use the first one:

Do While intX < 3
    intX += 1
Loop

and

While intX < 3
    intX += 1
End While

Nested Loops

You might need to start a loop even though you’re already working through another loop. This is known as nesting, and it’s similar in theory to the nesting demonstrated when you looked at If statements.

In this Try It Out, you’ll see how you can create and run through a loop, even though you’re already working through another one.

  1. In the Forms Designer, add another Button control to your form and set its Name property to btnNestedLoops and its Text property to Nested Loops.

  2. Double-click the button and add the following bolded code to its Click event handler:

    Private Sub btnNestedLoops_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles btnNestedLoops.Click
    
        ‘Clear the list
        ClearList()
    
        ‘Process an outer loop
        For intOuterLoop As Integer = 1 To 2
            ‘Process a nested (inner) loop
            For intInnerLoop As Integer = 1 To 3
                lstData.Items.Add(intOuterLoop.ToString & _
                    ″, ″ & intInnerLoop.ToString)
            Next
        Next
    End Sub
    
  3. Run the program and click the Nested Loops button. You should see results that look like those shown in Figure 4-23.

    Form1

    FIGURE 4-23

This code is really quite simple. Your first loop (outer loop) iterates intOuterLoop from 1 to 2, and the nested loop (inner loop) iterates intInnerLoop from 1 to 3. Within the nested loop, you have a line of code to display the current values of intOuterLoop and intInnerLoop:

‘Process an outer loop
For intOuterLoop As Integer = 1 To 2
    ‘Process a nested (inner) loop
    For intInnerLoop As Integer = 1 To 3
        lstData.Items.Add(intOuterLoop.ToString & _
            ″, ″ & intInnerLoop.ToString)
    Next
Next

Each For statement must be paired with a Next statement, and each Next statement that you reach always "belongs" to the last created For statement. In this case, the first Next statement you reach is for the 1 To 3 loop, which results in intInnerLoop being incremented. When the value of intInnerLoop gets to be 4, you exit the inner loop.

After you’ve quit the inner loop, you hit another Next statement. This statement belongs to the first For statement, so intOuterLoop is set to 2 and you move back to the first line within the first, outer loop—in this case, the other For statement. Once there, the inner loop starts once more. Although in this Try It Out you’ve seen two For…Next loops nested together, you can nest Do…While loops and even mix them, so you can have two Do…Loop statements nested inside a For loop and vice versa.

Quitting Early

Sometimes you don’t want to see a loop through to its natural conclusion. For example, you might be looking through a list for something specific, and when you find it, there’s no need to go through the remainder of the list.

In this Try It Out, you’ll look through folders on your local drive, but this time, when you get to c:\Program Files, you’ll display a message and quit.

  1. Return to the Forms Designer, add another Button control to your form, and set its Name property to btnQuittingAForLoop and its Text property to Quitting A For Loop.

  2. Double-click the button and add the following bolded code to the Click event handler:

    Private Sub btnQuittingAForLoop_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles btnQuittingAForLoop.Click
    
        ‘Clear the list
        ClearList()
    
        ‘List each folder at the root of your C drive
        For Each strFolder As String In _
            My.Computer.FileSystem.GetDirectories(″C:\″)
    
            ‘Add the item to the list
            lstData.Items.Add(strFolder)
    
            ‘Do you have the folder C:\Program Files?
            If String.Compare(strFolder, ″c:\program files″, True) = 0 Then
    
                ‘Tell the user MessageBox.Show(″Found it, exiting the loop now.″, ″Loops″)
    
                ‘Quit the loop early
                Exit For
    
            End If
        Next
    End Sub
    
  3. Run the program and click the Quitting a For Loop button. You’ll see something similar to the results shown in Figure 4-24.

    Loops - Found it, exiting the loop now.

    FIGURE 4-24

This time, with each iteration, you use the String.Compare method that was discussed earlier to check the name of the folder to see whether it matches C:\Program Files:

‘Do you have the folder C:\Program Files?
If String.Compare(strFolder, ″c:\program files″, True) = 0 Then

If it does, then the first thing you do is display a message box:

‘Tell the user
MessageBox.Show(″Found it, exiting the loop now.″, ″Loops″)

After the user has clicked OK to dismiss the message box, you use the Exit For statement to quit the loop. In this instance, the loop is short-circuited, and Visual Basic 2010 moves to the first line after the Next statement:

‘Quit the loop early
Exit For

Of course, if the name of the folder doesn’t match the one you’re looking for, you keep looping. Using loops to find an item in a list is one of their most common uses. Once you’ve found the item you’re looking for, using the Exit For statement to short-circuit the loop is a very easy way to improve the performance of your application. The Exit For statement will only exit one loop at a time so if you are nesting loops be sure to exit the correct one.

Imagine you have a list of a thousand items to look through. You find the item you’re looking for on the tenth iteration. If you don’t quit the loop after you’ve found the item, you’re effectively asking the computer to look through another 990 useless items. If, however, you do quit the loop early, you can move on and start running another part of the algorithm.

Quitting Do…Loops

As you might have guessed, you can quit a Do…Loop in more or less the same way, as you see in the next Try It Out.

In this example, you will use Exit Do to quit a Do…Loop.

  1. Return to the Forms Designer one last time and add another Button control to your form. Set its Name property to btnQuittingADoLoop and its Text property to Quitting a Do Loop.

  2. Double-click the button and add the following bolded code to the Click event handler:

    Private Sub btnQuittingADoLoop_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles btnQuittingADoLoop.Click
    
        ‘Declare variable
        Dim intCount As Integer = 0
    
        ‘Clear the list
        ClearList()
    
        ‘Process the loop
        Do While intCount < 10
    
            ‘Add the item to the list
            lstData.Items.Add(intCount.ToString)
    
            ‘Increment the count by 1
            intCount += 1
    
            ‘Should you quit the loop
            If intCount = 3 Then
    
    Exit Do
            End If
    
        Loop
    End Sub
    
  3. Run the project and click the Quitting a Do Loop button. You’ll see a list containing the values 0, 1, and 2.

In this case, because you’re in a Do…Loop, you have to use Exit Do, rather than Exit For. However, the principle is exactly the same. Exit Do will work with both the Do While…Loop and Do Until…Loop loops.

Infinite Loops

When building loops, you can create something called an infinite loop. This is a loop that, once started, will never finish. Consider this code:

Dim intX As Integer = 0
Do
    intX += 1
Loop Until intX = 0

This loop will start and run through the first iteration. Then, when you execute Loop Until intX = 0 the first time, intX is 1. Therefore, you return to the start of the loop again and increment intX to 2, and so on. What’s important here is that it will never get to 0. The loop becomes infinite, and the program won’t crash (at least not instantly), but it may well become unresponsive.

When you suspect a program has dropped into an infinite loop, you need to force the program to stop. If you are running your program in Visual Studio 2010, flip over to it, and select Debug ⇨ Stop Debugging from the menu. This will immediately stop the program. If you are running your compiled program, you’ll need to use the Windows Task Manager. Press Ctrl+Alt+Del and select Task Manager. Your program should appear as Not Responding. Select your program in the Task Manager and click End Task. Eventually this opens a dialog indicating that the program is not responding (which you knew already) and asking whether you want to kill the program stone dead, so click End Task again.

In some extreme cases, the loop can take up so much processing power or other system resources that you won’t be able to open Task Manager or flip over to Visual Studio. In these cases, you can persevere and try to use either of these methods; or you can reset your computer and chalk it up to experience.

Visual Studio 2010 does not automatically save your project before running the application the first time, so you’re likely to lose all of your program code if you have to reset. Therefore, it would be wise to save your project before you start running your code.

Summary

This chapter took a detailed look at the various ways that programs can make decisions and loop through code. You first saw the alternative operators that can be used with If statements and examined how multiple operators can be combined by using the And and Or keywords. Additionally, you examined how case-insensitive string comparisons could be performed.

You then looked at Select Case, an efficient technique for choosing one outcome out of a group of possibilities. Next you examined the concept of looping within a program and were introduced to the two main types of loops: For loops and Do loops. For loops iterate a given number of times, and the derivative For Each loop can be used to loop automatically through a list of items in a collection. Do While loops iterate while a given condition remains True, whereas Do Until loops iterate until a given condition becomes True.

In summary, you should know how to use:

  • If, ElseIf, and Else statements to test for multiple conditions

  • Nested If statements

  • Comparison operators and the String.Compare method

  • The Select Case statement to perform multiple comparisons

  • For…Next and For…Each loops

  • Do…Loop and Do While…Loop statements

Topic

Concepts

Comparison Operators

To compare items, you can use the following operators: >, >=, <, <=, =, <>, And, Or.

Using If

Use If statements to make decisions. For multiple decisions, you can also use If…Else or ElseIf. You can nest If…Else statements for more complex decisions. For simple decisions, you can even use a single-line If statement.

Using Select Case

Use Select Case to test an item for one of many possible values. To make sure you find a match, use the Case Else statement.

Using For Loops

Use For Loops to execute tasks for a certain number of times. The statement Exit For is used to quit a For Loop.

Using Do Loops

Use Do Loops to execute tasks while or until a condition is reached. The statement Exit Do is used to quit a Do Loop.

Exercise

When using a Select Case statement, how do you allow for multiple items in the Case statement?

What is the difference between a Do Until and a Loop Until Do loop?

Is "Bryan" and "BRYAN" the same string as Visual Basic sees it?

When you use the string.compare method, what is the last parameter (a Boolean parameter) used for?

In a Select Case statement, how do you put in a catch all case for items that do not have a match?

When writing a For Each Loop, how do you have the loop iterate backwards?

What keyword do you use to exit a loop early?

Beginning Microsoft® Visual Basic 2010, Copyright © 2010 by Wiley Publishing, Inc., ISBN: 978-0-470-50222-8, Published by Wiley Publishing, Inc., All Rights Reserved. Wrox, the Wrox logo, Wrox Programmer to Programmer, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc and/or its affiliates.