Changes

Jump to: navigation, search

Visual Basic Flow Control

2,962 bytes added, 15:30, 8 August 2007
Evaluating Multiple Possibilities using Select Case
<pre>
Dim strCity As String = "London" Dim strCountry As String
Select Case strCity Case "Paris" Message strCountry = "France" Case "London" strCountry = "England" Case "Berlin" strCountry = "Germany" End Select  MessageBox.Show("Welcome to " & strCountry) </pre> It is also possible to specify more than one option per Case statement: <pre> Dim strCity As String = "Munich" Dim strCountry As String  Select Case strCity Case "Paris", "St. Tropez" strCountry = "France" Case "London", "Sheffield", "Dover" strCountry = "England" Case "Berlin", "Munich" strCountry = "Germany" End Select  MessageBox.Show("Welcome to " & strCountry)</pre> One of the most powerful aspects of the Visual Basic ''Select Case'' construct (and a feature that is missing from the Select Case implementations in other programming languages) is the ability to specify a range of matches for a case statement. For example, the following code excerpt specifies acceptable value ranges for an integer match: <pre> Dim intSize As Integer = 6 Dim strSize As String  Select Case intSize Case 0 To 4 strSize = "Small" Case 5 To 8 strSize = "Medium" Case 9 To 12 strSize = "Large" End Select  MessageBox.Show("Shirt size is " & strSize)</pre> == Using the Visual Basic ''GoTo'' Statement == The Visual Basic ''GoTo'' statement provides a way for program execution to jump to a labeled location in the code. Before going into detail of how to use the ''GoTo'' statement it is important to be aware that the use of the ''GoTo'' statement is generally considered to be bad programming practice. A programmer under pressure will often reach for the GoTo statement when they have programmed themselves into a corner and need some way of getting to another section of code. Almost without exception, a ''GoTo'' jump should never be needed if the code had been carefully planned in the first place. If you find yourself tempted to use a ''GoTo'' jump, take some time to step back from the code and make sure there is not a more elegant solution. Avoiding excessive ''GoTo'' statements will make the code easier to maintain and debug. With that disclaimer we will now look at how to use a ''GoTo'' statement. As mentioned previously, The ''GoTo'' statement simply allows us to jump to a labeled code location somewhere else in an application. One valid use, which we will use in this example, is to exit a subroutine or function when an error is found: <pre>Private Sub ValidateValue(ByVal intValue As Integer) If intValue > 10 Then GoTo EXIT_SUB else ProcessValue(intValue) MessageBox.Show("Valid Number Entered") Endif EXIT_SUB: Exit SubEnd Sub
</pre>

Navigation menu