Exploring the Conditional Control Structure


The conditional control structure is used to conditionally execute a set of instructions. The syntax for the conditional control structure, in its simplest form, is given as

If condition Then    Instruction1    Instruction2    ...    InstructionN End If 


Here, condition is a Boolean expression, one that evaluates to either true or False. If condition evaluates to true, instructions Instruction1 through InstructionN are executed. If condition evaluates to False, Instruction1 through InstructionN are skipped and therefore are not executed.

By the Way

Conditional statements are commonly referred to as If statements.


Recall from the preceding hour that the comparison operators always return a Boolean value. These operators are commonly used to compare the values of two variables or the value of a variable with a literal. For example, with Visual Basic the current hour can be determined via the following code:

DateTime.Now.Hour 


This returns an integer value between 0 and 23, where 0 is midnight, 9 is 9:00 in the morning, 13 is 1:00 in the afternoon, and so on. We could create a simple ASP.NET web page that uses a conditional statement to determine the current hour and display an appropriate message based on the hour of the day (good morning versus good afternoon versus good evening).

Let's create such an ASP.NET web page. To start, create a new ASP.NET website on your personal computer's file system. Next, add a new ASP.NET page named TimeAppropriateMessage.aspx.

By the Way

Remember, when adding a new ASP.NET page to a website in Visual Web Developer, select the Web Form item type from the Add New Item dialog box. Also, be sure that the Place Code in Separate File check box is checked and that the Language choice is set to Visual Basic.


First, let's add a Label Web control that will display the message. From the Toolbox, drag and drop the Label Web control onto the page. Next, from the Properties window, change the Label's ID property to lblMessage and clear out the Label's Text property. Your screen should look similar to Figure 6.1.

Figure 6.1. A Label control has been added.


We now want to create some code that will run every time the ASP.NET page is visited. To accomplish this, create an event handler for the page's Load event. You can accomplish this in one of two ways: either double-click the page in the Design view, or go to the ASP.NET page's source code portion and select Page Events from the left drop-down list and Load from the right one.

After you have created the Page_Load event handler, enter the code shown in Listing 6.1.

Listing 6.1. A Different Message Is Displayed Based on the Current Hour

[View full width]

 1: Partial Class TimeAppropriateMessage  2:     Inherits System.Web.UI.Page  3:  4:     Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)  Handles Me.Load  5:         If DateTime.Now.Hour >= 6 And DateTime.Now.Hour < 12 Then  6:             lblMessage.Text = "Good morning."  7:         End If  8:  9:         If DateTime.Now.Hour >= 12 And DateTime.Now.Hour <= 17 Then 10:             lblMessage.Text = "Good afternoon." 11:         End If 12: 13:         If DateTime.Now.Hour > 17 Or DateTime.Now.Hour < 6 Then 14:             lblMessage.Text = "Good evening." 15:         End If 16:     End Sub 17: End Class 

After you enter the code in Listing 6.1 into your ASP.NET web page's source code portion, view it through a browser by going to the Debug menu and choosing Start Without Debugging. You should see the message "Good morning" if the current hour is after 6 a.m. but before noon, "Good afternoon" if it's past noon and before 5 p.m., and "Good evening" if it's after 5 p.m. and before 6 a.m.

By the Way

Notice that the message displayed to you is based on the current time of the machine where the web server is running. This means that if your ASP.NET web page is being hosted by a web-hosting company that is another time zone, the output you see may not be reflective of the current time in your time zone.


The code in Listing 6.1 works by using three If statements. The first If statement (lines 57) checks to see whether the current hour is greater than or equal to 6 and less than 12.

Note that the condition on line 5 contains two conditional statements: DateTime.Now.Hour >= 6 and DateTime.Now.Hour < 12. These two conditions are joined by the keyword And. Visual Basic contains two keywords for joining conditional statements: And and Or. The semantics of And and Or are just like their English counterparts. That is, the expression condition1 And condition2 will return TRue if and only if both condition1 and condition2 are true, whereas the expression condition1 Or condition2 will return true if either condition1 is true or condition2 is true (or if both condition1 and condition2 are true).

Did you Know?

Parentheses can be used to specify order of operations and to help make compound conditionals more readable. For example, if we wanted to run a sequence of instructions if the hour was between 9 and 12, or if the hour was 17, then we could use a statement like this:

[View full width]

If (DateTime.Now.Hour >= 9 AND DateTime.Now.Hour <= 12) OR (DateTime.Now.Hour = 17) then ' ... Instructions ... End If



So, if the current hour is both greater than or equal to 6 and the current hour is less than 12, then the condition on line 2 is true, and line 3 will be executed, which causes the message "Good morning" to be displayed.

Another conditional statement is found on line 9. This one checks to see whether the current hour is between noon and 5 p.m. (Because the hour is returned as a value between 0 and 23, 5 p.m. is returned as 17.) If the hour is both greater than or equal to 12 and less than or equal to 17, then line 7 is executed and the message "Good afternoon" is displayed.

A third condition on line 13 checks to see whether the hour is greater than 17 or whether the hour is less than 6. If either of these conditions is true, then the code on line 11 is executed, which displays the message "Good evening".

By the Way

Note that all three of these conditional statements are executed, but only one of the three conditionals will return true, meaning only one of the three messages will be displayed.


Executing Instructions If the Conditional Is False

As we have seen, the If statement executes a set of instructions if the supplied conditional is true. But what if we want to execute some instructions if the condition is false? For example, say that there is some string variable named password that contains the password for the user visiting our website. If the password variable is equal to the string "shazaam", we want to display some sensitive information; if, however, the password is not "shazaam", then the user has an incorrect password, and we want to display a warning message.

In this scenario we want to use an If statement because we want to execute one piece of code if the password is correct and another piece of code if the password is incorrect. We can accomplish this using the If statement as we saw earlier, like so:

If password = "shazaam" then   'Display sensitive information End If If password <> "shazaam" then   'Display message informing the user they've entered an   'incorrect password End If 


However, there is an easier way to accomplish this. An If statement can contain an optional Else clause. The source code that appears within the Else portion is executed when the condition evaluates to False. The general form of an If statement with an Else clause is

If condition Then    Instruction1    Instruction2    ...    InstructionN Else    ElseInstruction1    ElseInstruction2    ...    ElseInstructionN End If 


Here, if condition is true, then Instruction1 through InstructionN are executed, and ElseInstruction1 through ElseInstructionN are skipped. If, however, condition is false, then ElseInstruction1 through ElseInstructionN are executed, and Instruction1 through InstructionN are skipped.

Using the Else statement, we can rewrite the password-checking code from two conditionals to one, as in the following code:

If password = "shazaam" then   'Display sensitive information Else   'Display message informing the user they've entered an   'incorrect password End If 


Did you Know?

An If statement can have either no Else clause or precisely one Else clause. There cannot be multiple Else clauses for a single If statement.


Performing Another If Statement When the Condition Is False

In addition to the Else statement, If statements can have zero to many optional ElseIf statements. An ElseIf clause follows an If statement, much like the Else. The ElseIf clause has a condition statement like the If statement. The instructions directly following the ElseIf are executed only if the If statement's condition, as well as all of the preceding ElseIf conditions, are false and the condition of the ElseIf in question is true.

This description may sound a bit confusing. An example should help clear things up. First, note that the general form of an If statement with ElseIf clauses is as follows:

If condition Then    Instruction1    Instruction2    ...    InstructionN ElseIf elseIf1Condition    ElseIf1Instruction1    ElseIf1Instruction2    ...    ElseIf1InstructionN ElseIf elseIf2Condition    ElseIf2Instruction1    ElseIf2Instruction2    ...    ElseIf2InstructionN ... ElseIf elseIfNCondition    ElseIfNInstruction1    ElseIfNInstruction2    ...    ElseIfNInstructionN Else    ElseInstruction1    ElseInstruction2    ...    ElseInstructionN End If 


If the condition is true, then the instructions Instruction1 through InstructionN are executed and the other instructions are skipped. If, however, condition is false, then the first ElseIf condition, elseIf1Condition, is evaluated. If this condition is true, then instructions ElseIf1Instruction1 through ElseIf1InstructionN are executed. If, however, elseIf1Condition is false, then the second ElseIf condition, elseIf2Condition, is evaluated. Again, if it is true, then instructions ElseIf2Instruction1 through ElseIf2InstructionN are executed. If, however, elseIf2Condition is false, then the third ElseIf condition is evaluated, and so on. If all ElseIf conditions are false, then the Else's instructions (ElseInstruction1 through ElseInstructionN) are executed.

Let's return to the TimeAppropriateMessage.aspx example, whose source code was displayed in Listing 6.1. Take a moment to look back over that code listing; notice that we used three conditions: one to check whether the time was between 6 a.m. and 11 a.m., one to check whether the time was between noon and 5 p.m., and one to check whether the time was after 5 p.m. or before 6 a.m.

We can accomplish this with a single If statement using either two ElseIfs or one ElseIf and an Else. The code for using two ElseIfs is as follows:

If DateTime.Now.Hour >= 6 And DateTime.Now.Hour < 12 then   lblMessage.Text = "Good morning." ElseIf DateTime.Now.Hour >= 12 And DateTime.Now.Hour <= 17 then   lblMessage.Text = "Good afternoon." ElseIf DateTime.Now.Hour > 17 Or DateTime.Now.Hour < 6 then   lblMessage.Text = "Good evening." End If 


The code for using an ElseIf and an Else looks like this:

If DateTime.Now.Hour >= 6 And DateTime.Now.Hour < 12 then   lblMessage.Text = "Good morning." ElseIf DateTime.Now.Hour >= 12 And DateTime.Now.Hour <= 17 then   lblMessage.Text = "Good afternoon." Else   lblMessage.Text = "Good evening." End If 





Sams Teach Yourself ASP. NET 2.0 in 24 Hours, Complete Starter Kit
Sams Teach Yourself ASP.NET 2.0 in 24 Hours, Complete Starter Kit
ISBN: 0672327384
EAN: 2147483647
Year: 2004
Pages: 233

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