Lesson 11 - Conditional If Statements

Tutorial Series: Free C# Fundamentals via ASP.NET Web Apps

Previous Article  |  Next Article


Get GitHub Code

This lesson will cover changing the flow of code using conditional logic. You will be making if() statements in code that represent paths that your code can take - like a fork in the road - branching off in different directions depending on whether or not a particular condition is met. In addition to this, we will introduce new Server Controls like the CheckBox that give you more flexibility and options with your code.

Available for use in the Before folder of the provided code is a started project, with the Server Controls already in place. If you choose to use this, continue to step 2, otherwise follow the directions below.

Step 1: Create a New Project

Create a new ASP.NET project and call it “CS-ASP_011,” and in Design Mode set up Default.aspx as follows:

cs-asp-011---conditional-if-statements.001

The programmatic IDs for these Controls are:

  1. firstTextBox

  2. secondTextBox

  3. okButton

  4. resultLabel

The purpose of this application will be to evaluate what the user enters for each TextBox Control. A message will then be displayed depending on whether or not the values are considered to be equivalent.

Step 2: Create an if() Statement

First, double-click the okButton to create an EventHandler for the okButton_Click event. Write an empty if() statement inside of this code block:

cs-asp-011---conditional-if-statements.002

The part inside the parentheses that says “true” will be replaced by an expression that will be evaluated as either true or false. The squiggly brackets directly beneath this if() statement contain a code block that will execute only in the case that the expression evaluates as true. Let’s now evaluate whether or not each TextBox is equivalent to the other:

cs-asp-011---conditional-if-statements.003

Step 3: The Equivalence (==) Operator

Notice that we are using the double-equal’s sign, which is the equivalence operator. The assignment operator (=) is used to make two values equivalent, i.e. resultLabel.Text = "Hi". In this example, we don't want to assign anything at all, we just want to check for equivalence, which is why we use the equivalence operator. Now, let’s specify what happens if the values entered for each TextBox are equivalent and test it out by running the application:

cs-asp-011---conditional-if-statements.004

cs-asp-011---conditional-if-statements.005

Step 4: Clear Out resultLabel.Text on Button Click

You may notice that once the message is displayed, it will continue to stay there even when inequivalent values are set, because we never change its value. What we will need to do is reset resultLabel.Text each time the okButton_Click event is run. We achieve this by initializing the resultLabel.Text to an empty string. And now, when inequivalent values are entered, the code will completely skip the conditional code block leaving an empty resultLabel.Text to display:

resultLabel

Step 5: Add an else() Clause to the If() Statement

But what if we want to display a message in the event that the values are nonequivalent? Logically speaking, we need to run another conditional check to catch this event. However, in this case there are only two possible results: The values are equivalent or they are not. In these cases, an else() clause will satisfy the requirement by catching the outlying case. In English, the logic would go like this: If the values are equivalent, do this. Else, do this:

cs-asp-011---conditional-if-statements.007

cs-asp-011---conditional-if-statements.008

Tip:

The key point worth noting about conditional statements is how execution flow changes depending on whether or not the condition evaluates as true. Your application can have entire functions that are never used unless certain conditions are met. This allows applications to be more dynamic than simply executing one line after the other, flowing in a static pattern.

Step 6: Add a CheckBox Server Control

Next, add a CheckBox Server Control in the Defalut.aspx between the TextBoxes and the okButton:

cs-asp-011---conditional-if-statements.011

Now set the programmatic ID for this CheckBox to “coolCheckBox,” and set the text to “Are you cool?” Also, notice how the CheckBox can be initialized in the Properties window to one of two possible boolean values (true or false).

cs-asp-011---conditional-if-statements.012

In the okButton_Click event, comment out the previous conditional block and create a new one to determine what happens whether or not the CheckBox is checked, using the Checked property. If it is checked, change the Text property of the resultLabel:

cs-asp-011---conditional-if-statements.013

cs-asp-011---conditional-if-statements.014

cs-asp-011---conditional-if-statements.015

Step 7: Using Bools as Expressions in If() Statements

The conditional being evaluated here is the current state of coolCheckBox.Checked. Since it is a bool, and is inherently either true or false, we don’t even have to include the reference to “true” in the evaluation. Because of this, you can just write:

cs-asp-011---conditional-if-statements.016

Tip:

This is true of all variables or properties that are boolean in nature. The if() conditional is already checking to see if the value is true, so you can save yourself time and simplify your code by simply checking the property.

Step 8: Add a RadioButton Server Control

Now back in the designer, add three separate RadioButton Controls to Default.aspx, and change the Text properties of each to what follows:

cs-asp-011---conditional-if-statements.017

cs-asp-011---conditional-if-statements.018

Make the respective programmatic ID’s as follows:

  1. pizzaRadioButton

  2. saladRadioButton

  3. pbjRadioButton

Step 9: Add an else if() Clauses Between if() and else()

To evaluate all of these CheckBoxes, we could write out separate if() statements to check which RadioButton is selected in the okButton_Click event. However, there is a much more elegant and intuitive way to handle multiple possibilities, and that is by sandwiching else if() statements in between if() and else() statements. Comment out the previous conditional code blocks and create this new set:

cs-asp-011---conditional-if-statements.019

Whereas the else() statement does not check a condition because it always runs when the other code checks are false, the else if() does take in a condition. This means that the else if() code blocks will only execute if a) all preceding if() or else if() statements are false, and b) their condition is true. Otherwise, the final else() statement will execute.

When you run the application now you will see the result of these multiple, branching conditionals:

cs-asp-011---conditional-if-statements.020

Tip:

The if(), else if(), else() set of conditional statements cannot be done out of order. You must always start with a single if() statement, and (optionally) end with a single else() statement. Any number of else if() statements can be included, but these always have to come between the if() and else() statements.

Step 10: Group the RadioButtons

RadioButtons are meant to be mutually exclusive selections; in other words, only a single RadioButton can be selected at any given moment. However, there is a problem in our code because at the moment we can select as many as we want:

cs-asp-011---conditional-if-statements.022

What we need to do is make each RadioButton a part of a group. This can be achieved by setting the GroupName property for each Radio Button. To do this, change each GroupName to “FoodGroup”:

cs-asp-011---conditional-if-statements.023

Also worth mentioning is that the application does not let you deselect a RadioButton, it only lets you change a selection from one to another. This means that the only case where the final else() clause will execute is if we never make a single selection, yet press the “OK” button anyways:

cs-asp-011---conditional-if-statements.024

Step 11: Setting a Default Value for the RadioButton

Note that we can force a selection and eliminate the need for the final else() clause by setting the default Checked value of one of the RadioButtons to “True”:

cs-asp-011---conditional-if-statements.025

This covers the basics of conditional statements in C#. You've learned how to create if(), else if() and else() statements to evaluate properties and values. In the future, we'll cover the switch statement, which handles more complex conditional logic, but for all our needs right now, these statements will be sufficient. Good job so far, keep it up!


Related Articles in this Tutorial:

Lesson 1 - Series Introduction

Lesson 2 - Installing Visual Studio 2015

Lesson 3 - Building Your First Web App

Lesson 4 - Understanding What You Just Did

Lesson 5 - Working with Projects in Visual Studio

Lesson 6 - Simple Web Page Formatting in Visual Studio

Challenge 1

Solution 1

Lesson 7 - Variables and Data Types

Lesson 8 - Data Type Conversion

Lesson 9 - Arithmetic Operators

Lesson 10 - C# Syntax Basics

Challenge 2 - ChallengeSimpleCalculator

Solution - ChallengeSimpleCalculator

Lesson 11 - Conditional If Statements

Lesson 12 - The Conditional Ternary Operator

Challenge 3 - ChallengeConditionalRadioButton

Solution - Challenge Conditional RadioButton

Lesson 13 - Comparison and Logical Operators

Lesson 13 Challenge - First Papa Bob's Website

Solution - Challenge First Papa Bob's Website

Lesson 14 - Working with Dates and Times

Lesson 15 - Working With Spans of Time

Lesson 16 - Working with the Calendar Server Control

Challenge 4 - Challenge Days Between Dates

Solution - Challenge Days Between Dates

Lesson 17 - Page_Load and Page.IsPostBack

Lesson 18 - Setting a Break Point and Debugging

Lesson 19 - Formatting Strings

Challenge 5 - Challenge Epic Spies Assignment

Solution - Challenge Epic Spies Assignment

Lesson 20 - Maintaining State with ViewState

Lesson 21 - Storing Values in Arrays

Lesson 22 - Understanding Multidimensional Arrays

Lesson 23 - Changing the Length of an Array

Challenge 6 - Challenge Epic Spies Asset Tracker

Solution - Challenge Epic Spies Asset Tracker

Lesson 24 - Understanding Variable Scope

Lesson 25 - Code Blocks and Nested If Statements

Lesson 26 - Looping with the For Iteration Statement

Challenge 7 - Challenge For Xmen Battle Count

Solution - Challenge For Xmen Battle Count

Lesson 27 - Looping with the while() & do...while() Iteration Statements

Lesson 28 - Creating and Calling Simple Helper Methods

Lesson 29 - Creating Methods with Input Parameters

Lesson 30 - Returning Values from Methods

Lesson 31 - Creating Overloaded Methods

Lesson 32 - Creating Optional Parameters

Lesson 33 - Creating Names Parameters

Lesson 34 - Creating Methods with Output Parameters

Challenge 8 - Challenge Postal Calculator Helper Methods

Solution - Challenge Postal Calculator Helper Methods

Mega Challenge Casino

Solution - Mega Challenge Casino

Lesson 35 - Manipulating Strings

Challenge 9 - Phun With Strings

Solution - Challenge Phun With Strings

Lesson 36 - Introduction to Classes and Objects

Challenge - Hero Monster Classes Part 1

Solution - Hero Monster Classes Part 1

Challenge - Hero Monster Classes Part 2

Solution - Challenge Hero Monster Classes Part 2

Lesson 37 - Creating Class Files Creating Cohesive Classes and Code Navigation

Lesson 38 - Understanding Object References and Object Lifetime

Lesson 39 - Understanding the .NET Framework and Compilation

Lesson 40 - Namespaces and Using Directives

Lesson 41 - Creating Class Libraries and Adding References to Assemblies

Lesson 42 - Accessibility Modifiers, Fields and Properties

Lesson 43 - Creating Constructor Methods

Lesson 44 - Naming Conventions for Identifiers

Lesson 45 - Static vs Instance Members

Challenge 10 - Challenge Simple Darts

Solution - Challenge Simple Darts

Lesson 46 - Working with the List Collection

Lesson 47 - Object Initializers

Lesson 48 - Collection Initializers

Lesson 49 - Working with the Dictionary Collection

Lesson 50 - Looping with the foreach Iteration Statement

Lesson 51 - Implicitly-Typed Variables with the var Keyword

Challenge 11 - Challenge Student Courses

Solution - Challenge Student Courses

Mega Challenge War

Solution - Mega Challenge War

Lesson 52 - Creating GUIDs

Lesson 53 - Working with Enumerations

Lesson 54 - Understanding the switch() Statement

Lesson 55 - First Pass at the Separation of Concerns Principle

Lesson 56 - Understanding Exception Handling

Lesson 57 - Understanding Global Exception Handling

Lesson 58 - Understanding Custom Exceptions

Lesson 59 - Creating a Database in Visual Studio

Lesson 60 - Creating an Entity Data Model

Lesson 61 - Displaying the DbSet Result in an ASP.NET GridView

Lesson 62 - Implementing a Button Command in a GridView

Lesson 63 - Using a Tools-Centric Approach to Building a Database Application

Lesson 64 - Using a Maintenance-Driven Approach to Building a Database Application

Lesson 65 - Creating a New Instance of an Entity and Persisting it to the Database

Lesson 66 - Package Management with NuGet

Lesson 67 - NuGet No-Commit Workflow

Lesson 68 - Introduction the Twitter Bootstrap CSS Framework

Lesson 69 - Mapping Enum Types to Entity Properties in the Framework Designer

Lesson 70 - Deploying the App to Microsoft Azure Web Services Web Apps

Papa Bob's Mega Challenge

Papa Bob's Mega Solution Part 1 - Setting up the Solution

Papa Bob's Mega Solution Part 2 - Adding an Order to the Database

Papa Bob's Mega Solution Part 3 - Passing an Order from the Presentation Layer

Papa Bob's Mega Solution Part 4 - Creating the Order Form

Papa Bob's Mega Solution Part 5 - Adding Enums

Papa Bob's Mega Solution Part 6 - Creating an Order with Validation

Papa Bob's Mega Solution Part 7 - Calculating the Order Price

Papa Bob's Mega Solution Part 8 - Displaying the Price to the User

Papa Bob's Mega Solution Part 9 - Creating the Order Management Page


Comments

Please login or register to add a comment