Another important part of any program is flow control, which enables you to determine at runtime 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… and do… loops), and error-handling statements.
if statements are the form of conditional logic, also known as decision structures, that you will probably use most in your programs. They enable 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 Session variable for the logged-in user name (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"] == "" Response.Redirect("Login.aspx") }
In C#, if statements consist of the keyword if (case sensitive!), a predicate or condition expression, followed by the expression or block to be executed if the predicate evaluates to true. The if keyword is self-explanatory.
Note |
To index into the ASP.NET objects such as Session and Application, C# uses square brackets ([ and ]) rather than parentheses. If you use parentheses instead, you will get the compile time error message “ ‘Session’ denotes a property where a ‘method’ was expected.”, which may seem a little confusing. What this is telling you is that Session is a property that needs to be indexed using square brackets rather than a method, called with parentheses. |
A predicate is an expression that can be simple (as in the previous example) or quite complex, spanning multiple lines as needed. (Recall that C# ignores white space such as spaces, tabs, and newlines.) A predicate can contain multiple expressions that evaluate to true or false chained by && (logical AND) or || (logical OR) operators. For instance, the following predicate checks for the same Session variable as the previous example AND that a variable called Tries is not equal to 7:
if ( Session["LoggedInUserName"] == "" && Tries != 7 Response.Redirect("Login.aspx") }
In this example, if Session [“LoggedInUserName”] is not equal to an empty string, the test for Tries != 7 will not be evaluated. This is called Short-Circuit Evaluation. After C# determines that no matter whether an expression evaluates to true or false, the predicate will still evaluate to true or false, the additional expressions are not evaluated. In this example it would not matter, but in other examples one of the expressions might have a side effect of being evaluated (changing some variable or calling a method that does). Short-Circuit Evaluation also enables you to test expressions that might run quickly first, and then test those expressions that might take some time to run only if testing the expression could make a difference.
If the predicate evaluates to true, the single line or the block immediately below the if statement is executed. The following example would work exactly the same as the previous example:
if ( Session["LoggedInUserName"] == "" && Tries!=7 Response.Redirect("Login.aspx");
This if statement is different from virtually all other examples in this book in that it does not use curly braces. Why do I always use curly braces and have a single line if statement enclosed within a block? Imagine that I added one more line of code and ended up with the following:
// Bad example of what can happen when your indentation says on // thing, but the code something else if ( Session["LoggedInUserName"] == "" && Tries!=7 Tries++ Response.Redirect("Login.aspx");
Although my indentation means “If there is no logged in user and Tries is not equal to 7, increment Tries and redirect to Login.aspx,” what will really happen is that Tries will be incremented only if the predicate evaluates to true, and the user will always be redirected to Login.aspx. You should always use curly braces, no matter how simple the expression, as this will make your intent explicit, and make your code easier to read.
You can also provide code that will execute if the defined condition is false by adding the else statement. You can nest if and else statements as needed. These techniques are shown in the following example:
if ( Session["LoggedInUserName"] == "" Response.Redirect("Login.aspx") els if ( Session["LoggedInUserName"] == "SuperUser" ) Response.Write("You are a superuser!") els Response.Write("Hello, " + Session["LoggedInUserName"] + "!") }
Note |
C# enables you to place en entire if statement on a single line, such as the following: if ( 1 < 2 ) Response.Write("1 is less than 2"); This syntax should only be used for very simple if statements because it is inherently harder to read and debug single-line if statements. On occasion I might use such a construct when I need to have lots of if statements in a row and want to conserve space. Generally, rethinking the logic to find another way to conserve space is a better solution than placing all of the code for an if statement on a single line. |
Another form of conditional logic you’ll use frequently is the switch case statement. This statement is useful in situations where you can reasonably expect the defined condition you’re testing to evaluate to one of a limited number of values (or ranges of values). Unlike switch case statements in C++, C# switch case statements can switch not only on integer values, but on strings as well. For example, the following code checks to see which item of a listbox was chosen by a user and then it takes appropriate action:
switch(ColorString case "Red" Message.Text += "< font color='" + ColorString + "'>" Message.Text += "You chose Red" Message.Text += "</font>" break case "Green" Message.Text += "<font color='" + ColorString + "'>" Message.Text += "You chose Green" Message.Text += "</font>" break case "Blue" Message.Text += "<font color='" + ColorString + "'>" Message.Text += "You chose Blue" Message.Text += "</font>" break }
You can also add a default statement to execute specific code when the tested expression doesn’t match any of your listed values, as the following code demonstrates:
switch(ColorString case "Red" // .. case "Green" // .. case "Blue" // .. default Message.Text += "<font color='black'>" Message.Text += "You did not chose a color" Message.Text += "</font>" break }
It’s good programming practice to always have a default statement just in case there are unexpected values for the expression you’re testing (such as ColorString in this example). Note also that default is a C# keyword, so naming a class default (with a lowercase d) can be a problem. You might inadvertently end up trying to use default as a class name if you create a page default.aspx. Use Default.aspx (note the uppercase D) to avoid this, or better yet, use a different page name!
Note |
C++ programmers are used to sometimes not using a break statement at the end of every case to allow processing to “drop through” to the next case. Although there are some cases in which C# does allow this (documented in the C# Language Reference in the MSDN documentation), it is always safer to just include the break. |
Let’s actually use the switch case statement in a real Web Form. I will use several components that will be explained later in Chapter 9.
Open Visual Studio .NET.
On the File menu, choose New, and then click Project.
In the New Project dialog box, click the ASP.NET Web Application icon from the C# Project Type.
Name the project Chapter_03 as shown in the following illustration, and click OK.
You should see the Visual Studio .NET screen, as shown in the following illustration.
Move the mouse pointer over the Toolbox along the left side of the screen. It will expand. Drag a Label control onto the form, and then drag a DropDownList control onto the form and place it next to the label. Add another label to the form below the drop-down list and the other label. The form should look like the following illustration.
Click the drop-down list, and then in the Properties pane, change the ID from DropDownList1 to Color. Change AutoPostBack from False to True. In the drop-down list, scroll down to the Items property, click the ellipsis (…), and enter items for the drop-down list by clicking the Add button four times. Then click the Text box in the Properties pane for the first item and change it to Select a Color. Change the text box of the second item to Red, the third item to Green, and the fourth item to Blue. When the screen looks like the illustration on the following page, click OK.
Change the text of the label next to the drop-down list to Color. Change the ID of the label below the drop-down list to Message.
Double-click the drop-down list and a screen will appear, as shown in the following illustration.
This is the event handler that is called when the selected item in the drop-down list is changed by the user. This is covered more fully in Chapter 9.
Add the following code to the Color_SelectedIndexChanged event handler:
// Initialize label Message.Text = "" switch(Color.SelectedItem.Text case "Red" Message.Text += "<font color='" + Color.SelectedItem.Text + "'>" Message.Text += "You chose Red" Message.Text += "</font>" break case "Green" Message.Text += "<font color='" + Color.SelectedItem.Text + "'>" Message.Text += "You chose Green" Message.Text += "</font>" break case "Blue" Message.Text += "<font color='" + Color.SelectedItem.Text + "'>" Message.Text += "You chose Blue" Message.Text += "</font>" break default Message.Text += "<font color=\"black\">" Message.Text += "You did not chose a color" Message.Text += "</font>" break }
On the File menu, click Save All to save the page, and then on the Build menu, click Build Chapter_03 to compile the application.
Browse the page by right-clicking it in Solution Explorer, and then selecting View In Browser (or Browse With).
To select a color other than the default, click the down arrow to the right of the drop-down list, and click a color. A screen similar to the one shown in the following illustration will appear.
This simple example shows several features of ASP.NET and C# within Visual Studio .NET, including:
RAD development Drop controls on the form, and then handle events.
Codeless development The ability to set many properties on controls without any coding.
Automatic postbacks by controls other than buttons Every time you select an item from the list, the form actually posts back to the server. This allows for a much richer user interface than classic ASP.
Looping statements are useful features that enable you to perform actions repeatedly, by either specifying explicitly at design time the number of times the code should loop, deciding at runtime how many times to loop, 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 different situation. Loop types include
for… loops are useful for repeating a given set of statements a 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:
int i for ( i = 0 ; i<7 ; i++ ) Message.Text += "<font size=\"" + i + "\">Welcome to ASP.NET</font><br/>" }
Note |
In this example, I use a backslash (\) inside the string to escape the quotation mark (“). Quotation marks around the font size are required for properly formed HTML because they are used as the string delimiter. |
In this example, in addition to using the variable i, i could also be declared within the for… loop, as in this example:
for ( int i = 0 ; i < 7 ; i++ ) Message.Text += "<font size=\"" + i + "\">Welcome to ASP.NET</font><br/>" }
Every for… loop in C# consists of three parts, any of which can be empty:
Initialization In the previous example, int i = 0
Expression The test expression, evaluated like the predicate in the if statement
Iterators A statement to be run during each iteration of the loop
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:
string[] s = new string[5] s[0] = "A" s[1] = "B" s[2] = "C" s[3] = "D" s[4] = "E" for (int i = 0 ; i < s.Length ; i++ ) Message.Text += "<font size=\"" + i + "\">" Message.Text += s[i] Message.Text += "</font><br/>" }
Note |
Unlike Visual Basic .NET, declaring an array as I do in the example just shown creates an array of 5 elements, not an array with 0 as the lower bound and 5 as the upper bound (in fact 6 elements). |
foreach… loops are a specialization of for… loops that enable 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:
DateTime[] Dates Dates = new DateTime[3] Dates[0]=DateTime.Now Dates[1]=Dates[0].AddDays(7) Dates[2]=Dates[0].AddYears(1) foreach (DateTime dt in Dates Message.Text += dt.ToShortDateString() + "<br/>\n" }
This code outputs each date to the browser using Response.Write. Because the DateTime type contains a date and a time, I use ToShortDateString to format the date in away that shows only the date. Using foreach… loops completely eliminates any problem with indexing outside the bounds of the array.
do…while loops enable you to execute a set of statements repeatedly for as long as a test condition remains true. The condition contained in the while part of the statement is evaluated at the end of each cycle, and so code inside the loop is executed at least once. For example:
// do…while syntax int i = 1 do { Message.Text += "<font size=\"" + i + "\">Welcome to ASP.NET</font><br/>" i++ } while ( i <= 5 );
while… loops do essentially the same thing as do while… loops; they enable you to execute a given set of statements while a given condition is true. A while… loop that does the same thing as the preceding do…while loop would look like the following:
// while syntax i = 1; // Declared previously while ( i <= 5 Message.Text += "<font size=\"" + i + "\">Welcome to ASP.NET</font><br/>" i++ }
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.