Decision-Making


When a user clicks on a button in a web form, the code in the Button_OnClick event handler will be executed sequentially. When a web form is loaded for the first time, the code in the Page_Load event will be executed sequentially. The fact is that every line of code will execute sequentially from the first line to the last without branching. However, sometimes we need to do different things in different situations. We did this in Chapter 2 when we wrote our dice game – if the player rolled two ones, we ended the game and reset the score. Otherwise, we added the total of the two dice to the high score.

Let's take a more detailed look at how we can use Visual Basic .NET code to make decisions.

Making Decisions with If...Then

The If ... Then statement is the most common decision-making approach. Using this statement simply says "if this condition is true, then do the following steps."

When you go to bed, you probably do the following:

  1. Get ready for bed

  2. Set your alarm clock

  3. Go to bed

It's not quite that simple though. Depending on the day of the week, you might not need to bother setting the alarm clock. Therefore, your routine will be more like this:

Nothing complicated there. Let's translate this concept into a computer program:

Try It Out—The Basic If Statement

If you take a test at school, then chances are that there is a threshold mark to pass it. If a test score is above the pass mark, then that candidate will see the word "PASS" on the result slip. This is an example of a simple condition. We will translate this into a programming example that's quite easy to code. Let's get started.

  1. Create a new file named IfThen.aspx in Web Matrix.

  2. Start by entering the text Your score: into the designer, and add two more blank lines. Then drag a TextBox next to Your score:, and add a Button and Label control on each of the blank lines.

  3. Your page should now look like this:

    click to expand

  4. Change the Text property of the Button to Check Result and the Text property of the Label to be blank.

  5. Now we can start writing some code. Double-click the Check Result button to add a Button1_Click event handler and enter the following code:

    Sub Button1_Click(sender As Object, e As EventArgs)  Label1.Text = ""  ' Compare the entered score with a pass score, and set a   ' congratulations statement to Label1.Text if it is True  If CInt(TextBox1.Text) >= 50 Then  Label1.Text = "Congratulations! You passed the test!"  End If End Sub

    This will perform a comparison between the pass mark, 50 in this case, and whatever the user typed in, and then use this as a condition for the If ... Then statement.

  6. And that's all there is to it. Run the page by pressing F5, or clicking the Start button, and try entering a sample test score to check the result. After you enter a value above the pass mark and click Check Result, the screen should look like the following:

    click to expand

How It Works

If you run the page, type in 70 in the textbox, and click the Check Result button, ASP.NET will call the code in the Button1_Click event handler. The first line in the handler is:

Sub Button1_Click(sender As Object, e As EventArgs)   Label1.Text = ""

Hang on – we've already blanked the label's Text property in the Properties window, so what's this for? Be patient – this line of code is important, and we'll explain why in just a moment.

The next line of code after the two lines of comments beginning with a single quote (') is:

  If CInt(TextBox1.Text) >= 50 Then

The part between the If and the Then is the condition. If this statement is true, then the code between the Then and the End If will run. This condition says, "The number that the user typed into the textbox is bigger than or equal to 50." This statement will be either true or false. In our case, we entered 70, so it's true – the code between the Then and the End If runs and the message is displayed:

    Label1.Text = "Congratulations! You passed the test!"   End If

If the condition is not true, then the program will skip the block of code and execute the statement after the End If. In our case, there is no code after the End If so nothing is seen by the user.

What about that line of code at the start?

  Label1.Text = "" 

Once the code is run, the congratulations message is displayed in the label, and it will remain set until the next time the label is told to display a new message. The text of the label needs to be reset to blank each time the program is run otherwise the message will continue to be displayed no matter what value is entered into the textbox before the button is pressed. By setting it back to blank, it will then only be displayed again when a value is entered that passes the test.

Doing Something Else

The decisions we make in life are not this simple all the time, and our programs won't be either. Often, we want to do one thing if the condition is true, and something else if it is false.

This is easy in Visual Basic .NET – we just add an Else section to our If ... Then block, like this:

Sub Button1_Click(sender As Object, e As EventArgs)   ' Compare the entered score with a pass score, and set a  ' congratulations statement to Label1.Text if it is True,  ' otherwise, display a warning message   If CInt(TextBox1.Text) >= 50 Then     Label1.Text = "Congratulations! You passed the test!"  Else  Label1.Text = "Sorry, you have to try harder next time."   End If End Sub

Once the user clicks the button, the condition in the If ... Then statement will be evaluated. When the If condition is evaluated as True, the statements between Then and Else will be processed, and a congratulatory message will be displayed. Otherwise, the program will run the lines between Else and End If and a low score warning message will be displayed.

Now that we have added the Else statement, the value of the Label will be set every time the code is run, so we can remove the first line of the code that sets the value of the Label to blank.

Even More Choices – Using ElseIf

Conditions in our If statements must always be either true or false – either it is Sunday or it isn't, the score is either above 50 or it isn't, and so on. However, many conditions are more complicated than this – there are cases where more than two possible courses of action are conceivable.

To make more complicated decisions using a computer, we need to break the decision down into smaller true or false conditions. When you first start programming, you might find this tricky – how can complicated problems be turned into lots of really simple ones? You'll soon learn, though, that the world is much simpler than you think it is!

Try It Out—Multi-Choice If ... ElseIf Statements

Visual Basic .NET lets us add ElseIf in an If ... Then statement. In our exam results pass mark example, we can evaluate the result of a test as pass or fail by comparing it with a pass score. However, we want to display a special message to encourage those students who have achieved a very high mark (for example, 80 or above). This leaves us with three types of message:

  • One for students who failed, scoring lower than 50

  • One for students who passed with grades between 50 and 79

  • One for students who passed with a score of 80 or more.

Let's see how to implement this in our code.

  1. First of all, make a copy of the IfThenElse.aspx page we created from a modified version of IfThen.aspx. The easiest way to do this is by manipulating the files in Windows Explorer. Then, rename the page to ElseIf.aspx.

  2. Next, open up ElseIf.aspx and make the following changes to the code:

    Sub Button1_Click(sender As Object, e As EventArgs)   ' Compare the entered score with a pass score, and set a  ' message to Label1.Text according to the result of the condition  If CInt(TextBox1.Text) >= 80 Then  Label1.Text = "Well done!"  ElseIf CInt(TextBox1.Text) >= 50 Then     Label1.Text = "Congratulations! You passed the test!"   Else     Label1.Text = "Sorry, you have to try harder next time."   End If End Sub

  3. Run the page by pressing F5 or clicking the Start button, and try entering a numeric test score to check the behavior of code we have modified. After you have entered a high scoring mark and clicked Check Result, the page should look like this:

    click to expand

How It Works

This example originally showed a pass message if the user entered a score greater than or equal to 50, or a fail message if the score was less than 50.

Now, besides these two messages, one more specific message will be shown if the candidate gets a very high mark. So, we can divide the marks into three categories: distinction, pass, and fail. First, we will check whether the mark belongs to the distinction score. The program will check whether the entered score is greater than or equal to 80, if this comparison is True, then Label1's Text property will be set as Well done! immediately. This is due to the following code:

  If CInt(TextBox1.Text) >= 80 Then     Label1.Text = "Well done!"

If this condition is not true, then it may either belong to pass group or fail group. The next step is to know whether the mark is a pass (without distinction) or fail. If the entered score is smaller than 80 but greater than or equals to 50, it will be classified as pass as the second condition returns True:

  ElseIf CInt(TextBox1.Text) >= 50 Then     Label1.Text = "Congratulations! You passed the test!"

Finally, if the entered score returns False after evaluating with the all of the conditions above, then it will be treated as an Else case. So, the statement between Else and End If will be processed:

  Else     Label1.Text = "Sorry, you have to try harder next time."   End If

You can have as many ElseIf statements as you like, but remember that it does matter what order you put them in. The code goes through each one in turn, and will only execute the first one where the condition evaluates to true. For example:

  If CInt(TextBox1.Text) >= 50 Then     Label1.Text = "Congratulations! You passed the test!"   ElseIf CInt(TextBox1.Text) >= 80 Then     ' THIS WILL NEVER RUN!   Else     Label1.Text = "Sorry, you have to work hard next time."   End If

The ElseIf statement in this case will not run, because if the number tested is greater than 50 the If statement is exited after the first clause. Since only numbers less than 50 will be tested in the ElseIf condition, and no number can be both less than 50 and greater than 80, the statement will never evaluate to true, hence that part of the code will never be run.

Testing Multiple Conditions

By now, we can get Visual Basic .NET to make some pretty clever choices. Even so, real life is often a lot more complicated. For example, if I feel hungry and I have sufficient money, I will order a pizza. There are two conditions in this example – feeling hungry and having sufficient money. Both of these conditions must be true for me to be able to order pizza, unless I really feel like having a pizza without actually being hungry, but that's another story!

Try It Out—Testing Multiple Conditions

If the 13th day of a month is Friday, we will normally say something like, "Careful! Friday 13th is an unlucky day for some people!". Let's write a program to make sure we get a fair warning. We need to test for two conditions now – the day of the week being Friday, and the day of the month being the 13th.

  1. Create a new ASP.NET Page called MultipleConditions.aspx. and enter some introductory text, such as Please select a date:, and then add a blank line after it.

  2. Drag a Calendar control from the Web Controls tab in the Toolbox on the left onto the page and add one more blank line after this control. Place a Label control at the bottom of the page, which should now look like this:

    click to expand

  3. Change the Text property of the Label control to be blank in the Properties window.

  4. We can write some code with this calendar control now. Double-click on the Calendar control to add the Calendar1_SelectionChanged event handler, and enter the following code:

    Sub Calendar1_SelectionChanged(sender As Object, e As EventArgs)  If Day (Calendar1.SelectedDate) = 13 And _  Calendar1.SelectedDate.DayOfWeek = 5 Then  Label1.Text = "Careful! Friday 13th is an unlucky day for some people!"  Else  Label1.Text = "It's just another day in life..."  End If End Sub

    The first condition will test whether the selected date is the 13th day of the month, and the second condition is going to test whether the selected date is a Friday or not.

  5. That's it, we're done. Press F5 to run the example now, and try clicking on a date on the Calendar control. Depending on what day and date you click on, you will something like one of the two following screens:

    click to expand

    click to expand

The highlighted date in the Calendar control indicates the selected date. You can try clicking on a Friday 13th to see the warning in the code, or you can choose another day that does not meet either or both criteria and see the relevant message displayed.

How It Works

The Calendar control is a brand new rich control in ASP.NET, which we'll learn a bit more about in the next chapter. The SelectionChanged event handler is invoked if you click on any date on this control:

Sub Calendar1_SelectionChanged(sender As Object, e As EventArgs)

The first line of the event handler is:

  If Day (Calendar1.SelectedDate) = 13 And _     Calendar1.SelectedDate.DayOfWeek = 5 Then

Since this line is too long to fit on a printed page, I've used an underscore to split it over two lines. This is a good way to make your code more readable, especially when you're joining lots of conditions together. The underscore tells Visual Basic .NET to treat it as one line. You can type this line all on one line in your code if you prefer, since you are less likely to be constrained by physical page width!

In this statement, there are two conditions to be evaluated:

  • Day(Calendar1.SelectedDate) = 13 – Check the selected date of its corresponding month

  • Calendar1.SelectedDate.DayOfWeek = 5 – Check the day of week of the selected date. 0 is a Sunday while 6 is a Saturday.

Sometimes you will want to combine conditions in other ways. The most common of these is using Or instead of And:

  If Day(Calendar1.SelectedDate) = 13 Or _     Calendar1.SelectedDate.DayOfWeek = 5 Then  Label1.Text = "A bit dangerous, but you should be OK."   End If

Another useful trick is to say 'if one thing is true, and the other thing isn't true'. To test if something is not true, you just put Not in front of it:

  If Not Day(Calendar1.SelectedDate) = 13 And _     Calendar1.SelectedDate.DayOfWeek = 5 Then  Label1.Text = "Hooray, it's a safe Friday, have a good weekend!"   End If

This is saying "If it's not the thirteenth, but it is a Friday, then display the following message."

However, this is where things start getting a bit complicated. It's hard to tell whether this means "if it's not the thirteenth, and it's not a Friday, then display the message"... does the Not apply to the whole condition, or just the first one?

To make things clearer, we can put things in brackets like this:

  If (Not Day(Calendar1.SelectedDate) = 13) And _     Calendar1.SelectedDate.DayOfWeek = 5 Then     Label1.Text = "Hooray, it's a safe Friday, have a good weekend!"   End If

Now it's easy to see that the Not only applies to the first bit.




Beginning Dynamic Websites with ASP. NET Web Matrix
Beginning Dynamic Websites: with ASP.NET Web Matrix (Programmer to Programmer)
ISBN: 0764543741
EAN: 2147483647
Year: 2003
Pages: 141

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