Flow Control


Another important piece of any program is flow control, which allows you to determine at run time which sections of your code will run and in what order. Flow control statements are the foundation of business logic and consist of conditional logic (including If and Case statements), looping structures (For… andDo… loops), and error-handling statements.

If Statements

If statements are the decision structures that you will probably use most in your programs. They allow you to look for a defined logical condition in your program and execute a specific block of code if that condition is true. The following code checks a variable stored in the Session object for the logged-in username (set in the login page) to prevent a user who has not logged into your ASP.NET application from viewing pages that require a login:

If Session("LoggedInUserName") = "" Then Response.Redirect("Login.aspx") End If

In Visual Basic .NET, an If statement block always requires an accompanying End If statement to denote the close of the If block. You can also provide code that will execute if the defined condition is false by adding the Else statement, and you can test for more than one condition by using one or more ElseIf statements. These techniques are shown in the following example:

If Session("LoggedInUserName") = "" Then Response.Redirect("Login.aspx") ElseIf Session("LoggedInUserName") = "SuperUser" Then Response.Write("You are a superuser! ") Else Response.Write("Hello, " & Session("LoggedInUserName") & "!") End If

Note

Visual Basic .NET also supports single-line If statements, such as the following:

If 1 < 2 Then Response.Write("1 is less than 2")

This syntax should be used only for very simple If statements, since single-line If statements are inherently more difficult to read and debug.

Select Case Statements

Another decision structure you’ll use frequently is the Select Case statement. This statement is useful in situations in which you can reasonably expect the defined condition you’re testing to evaluate to one of a limited number of values (or ranges of values). For example, the following code checks to see which item of a list box was chosen by a user, and then it takes appropriate action.

Dim ColorString As String ColorString = Request.Form("Colors") Select Case ColorString Case "Red" Response.Write("<font color='" & ColorString & "'>") Response.Write("You chose Red") Response.Write("</font>") Case "Green" Response.Write("<font color='" & ColorString & "'>") Response.Write("You chose Green") Response.Write("</font>") Case "Blue" Response.Write("<font color='" & ColorString & "'>") Response.Write("You chose Blue") Response.Write("</font>") End Select

You can also add a Case Else statement to execute specific code when the tested expression doesn’t match any of your listed values, as the following code demonstrates:

Select Case ColorString Case "Red" '…  Case "Green" '… Case "Blue" Response.Write("<font color='" & ColorString & "'>") Response.Write("You chose Blue") Response.Write("</font>") Case Else Response.Write("<font color='Black'>") Response.Write("You did not choose a color") Response.Write("</font>") End Select

It’s good programming practice to always have a Case Else statement, just in case there are unexpected values for the expression you’re testing (such as ColorString in this example).

start example

Use Select Case in a Web Forms page

  1. Open Visual Studio .NET.

  2. Select New from the File menu, and then select Project.

  3. In the New Project dialog box, select Visual Basic Projects from the Project Types list and ASP.NET Web Application from the Templates list.

  4. Type http://localhost/Chapter_03 in the location text box. (The Name text box will show the new name as you type it.) Click OK.

    The project will be created and loaded into the IDE, as shown in the illustration on the following page.

    click to expand

  5. Move the mouse pointer over the Toolbox on the left side of the screen. The Toolbox will appear. Place a label, a drop-down list, and another label on the form, as shown in the following illustration.

    click to expand

  6. Click the first Label control, then use the Properties window to change its Text property to Color.

  7. Click on the DropDownList and then use the Properties window to change the ID property to Color. Change the AutoPostBack property to True.

  8. Select the Items property of the DropDownList, click on the ellipsis (…), and enter items for the DropDownList by clicking Add four times and then setting the Text property for the first list item to Select Color, the next to Red, the next to Green, and the fourth to Blue. Once the screen looks like the following illustration, click OK.

    click to expand

  9. Use the Properties window to change the ID property of the second label to Message.

  10. Double-click on the DropDownList.

    This will open the code-behind module for the page, and will also create the Color_SelectedIndexChanged event handler, as shown in the illustration on the following page.

    click to expand

  11. Add the following code to the Color_SelectedIndexChanged handler:

    Message.Text = "" 'initialize Text property Select Case Color.SelectedItem.Text Case "Red" Message.Text &= "<font color='" & _ Color.SelectedItem.Text & "'>" Message.Text &= "You Chose Red!" Message.Text &= "</font>" Case "Green" Message.Text &= "<font color='" & _ Color.SelectedItem.Text & "'>" Message.Text &= "You Chose Green!" Message.Text &= "</font>" Case "Blue" Message.Text &= "<font color='" & _ Color.SelectedItem.Text & "'>" Message.Text &= "You Chose Blue!" Message.Text &= "</font>" Case Else Message.Text &= "<font color='Black'>" Message.Text &= "You did not choose!" Message.Text &= "</font>"End Select 

  12. From the File menu, select Save WebForm1.aspx.vb to save the new code.

  13. From the Build menu, select Build Chapter_03 to compile the project.

  14. Browse the page by right-clicking it in Solution Explorer, and then selecting View In Browser (or Browse With).

  15. Select a color by clicking on the arrow on the right side of the drop- down list. The result should be similar to the following illustration.

    click to expand

end example

This simple example shows several features of ASP.NET and Visual Basic .NET within Visual Studio .NET, including:

  • Rapid Application Development (RAD), which allows you to just drop controls on the form and then handle events.

  • The ability to set many properties on controls without any coding.

  • Automatic postbacks by controls other than buttons, which allows for a much richer user interface than classic ASP; for example, every time you select an item from the list, the form actually posts back to the server, allowing you to send an updated response to the client.

Looping Statements

Looping statements are useful features that allow you to perform actions repeatedly, by either specifying explicitly at design time the number of times the code should loop, deciding at run time how many times to loop, looping until a specified condition is met, or looping through a collection of objects and taking a specific action on each item. There are several different types of looping statements, each of which has its own particular syntax and is useful for a particular situation:

  • For… loops

  • For Each… loops (a special case of For… loops)

  • Do… loops (which include Do While… and Do Until… loops)

  • While… End While loops

Note

NoteVisual Basic 6 supported the While…Wend syntax for While… loops. In Visual Basic .NET, this syntax is no longer supported. You should use the While…End While syntax instead.

Using For… Loops

For… loops are useful for repeating a given set of statements a specific number of times. The number of times the statements are executed can be determined either explicitly or by evaluating an expression that returns a numeric value.

The following example (from the ASP.NET QuickStart Tutorial) uses a For… loop that counts from 1 to 7 and, for each pass of the loop, outputs a message with a font size equal to the counter variable:

<% Dim I As Integer For I = 0 to 7 %> <font size="<%=I%>"> Welcome to ASP.NET </font> <br/> <% Next %>
Note

The preceding code example and several others in this section use the <% %> tags, which allow you to embed code directly into an .aspx page, which is also the way that classic ASP pages were typically written. While this is still valid in ASP.NET, it’s more common to place code in a server-side <script> block or in a code-behind class, which helps keep HTML and control tags separate from code, making both easier to maintain.

You can also use the Step keyword to loop by steps greater than 1, or even to loop backward by specifying a negative number, as follows:

<% Dim I As Integer For I = 7 To 0 Step -1 %> <font size="<%=I%>"> Welcome to ASP.NET </font> <br/> <% Next %>

You can also use a For… loop to loop through the elements of an array by specifying the length of the array as the loop count expression, as follows:

<% Dim s(4) As String s(0) = "A" s(1) = "B" s(2) = "C" s(3) = "D" s(4) = "E" For I = 0 To s.Length - 1 %> <font size="<%=I%>"> <%=s(I)%> </font> <br/> <% Next %>
Note

In Visual Basic .NET, all arrays are zero-based. Therefore, to use the Length property of the array for a looping statement, you should use Length –1. Note also that the array declaration Dim s(4) As String results in an array of 5 members (0 to 4).

Using For Each… Loops

For Each… loops are a specialization of For… loops that allow you to loop through a collection or group of elements and take action on each item. The following example demonstrates looping through the items in an array of dates:

Dim Dates(2) As Date Dim DateItem As Date Dates(0) = Now.Date Dates(1) = Now.AddDays(7).Date Dates(2) = Now.AddYears(1).Date For Each DateItem In Dates Response.Write("Date is: " & DateItem.ToString & ".<br/>") Next

Note

Now is a Visual Basic .NET keyword that returns a DateTime structure containing the current date and time. This is useful for getting current date and time information, or future dates/times based on the current date/time, as shown in the preceding example.

This code outputs each date to the browser using Response.Write. Note that when declaring the Dates array, you use the upper bound of 2 to specify 3 elements (0 to 2).

Using Do… Loops

Do… loops allow you to execute a set of statements repeatedly for as long as a test condition remains true. Do… loops (also known as Do… While loops) come in several variations. The most basic of these is shown in the following example:

<% 'Do While…Loop syntax: Dim I As Integer = 1 Do While I <= 5 %> <font size="<%=I%>"> Welcome to ASP.NET </font> <br/> <% I = I + 1 Loop %>

The statements within the loop will be executed as long as the variable I is less than or equal to 5. If, for whatever reason, I is greater than 5 the first time the Do statement is executed, the statements within the loop will not be executed. If you want to ensure that the statements within the loop will execute at least once, you can move the While expression to the end of the loop, as follows:

<% 'Do…Loop While syntax: Dim I As Integer = 0 Do I = I + 1 %> <font size="<%=I%>"> Welcome to ASP.NET </font> <br/> <% Loop While I < 5 %>

You can also use the Until keyword in place of While to test for a condition, which would give you the opposite result of While.

Ultimately, the only real difference between While or Until is that While will loop as long as its test condition evaluates to True, whereas Until will loop as long as its test condition evaluates to False.

Using While…End While Loops

While…End While loops do essentially the same thing as Do While… loops, letting you execute a given set of statements while a given condition is true.While… loops are not as flexible as Do… loops because they don’t offer theUntil keyword or allow the condition to be placed at the end of the loop ratherthan the beginning. An advantage of While…End While loops is that the simpler syntax might be easier for beginning programmers to use more consistently. A While… loop that does the same thing as the preceding Do… loops would look like the following:

<% 'While…End While syntax: Dim I As Integer = 1 While I <= 5 %> <font size="<%=I%>"> Welcome to ASP.NET </font> <br/> <% I = I + 1 End While %>

Most programs will use a variety of loop types. No matter which loop type you choose, the important thing is that you use it correctly and consistently for a given task. This will make your code easier to read and maintain.




Microsoft ASP. NET Programming with Microsoft Visual Basic. NET Version 2003 Step by Step
Microsoft ASP.NET Programming with Microsoft Visual Basic .NET Version 2003 Step By Step
ISBN: 0735619344
EAN: 2147483647
Year: 2005
Pages: 126

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net