Home » ASP.NET Basics » 07 - Writing code and handling events
7

The if-else statement

Defining function and uses of the if-else statement

Before we write some code using the if-else statement, let us look at the basic syntax of if-else.

 if (condition) {
statements to execute if the condition is true;
 } else {
statements to execute if the condition is false;
 }

Here, `if' and `else' are keywords. We test a condition with `if'. If that condition is true, the statements inside the block just after `if' will execute. If the condition is false, the statements inside the block after `else' will execute.

We can now apply this knowledge in a program to find if a given number is even or odd. Create a page with one TextBox control, one Button control and one Label control. Double click the button control. The following code segment will be visible in the source view (if we are using the inline model) or in the code behind file (if we are using the code behind model):

 protected void Button1_Click(object sender, EventArgs e) { }

This section is known as the Event Handler for the click event of the button. It means that whatever code we write inside the curly braces will run when the button is clicked. Type the following code so that the event handler looks like this:

 protected void Button1_Click(object sender, EventArgs e) { int number; number = Convert.ToInt32(TextBox1.Text); if (number % 2 == 0) { Label1.Text = "The number is Even"; } else { Label1.Text = "The number is Odd"; } }

Here is what is happening in the code:

First, we have declared an integer variable called `number' -

 int number; The next statement is - number = Convert.ToInt32 (TextBox1.Text); 

Here, we are first converting the value entered in the text box into an integer. Remember that values in the text box are text values. We cannot store this value directly in the number variable because the variable is of type integer. The Convert.ToInt32 will convert the text value into an integer value. Now we can store this value in the variable.

Note: If the user enters some text (a name, for example) instead of a number in the textbox, this method will fail. In a real life application, we should first check if the value entered is a valid number. This is called defensive coding.

The next statement checks if the number is divisible by 2.

 if (number % 2 == 0)

If this condition is true, the Label control will display "The number is Even". However, if the condition is not true, the statement inside the else block will execute and the Label control will display "The number is odd".

 [ifelese 1]
We can test multiple conditions using the if-else statement. For this, the syntax is:
 if (condition 1) {
 statements if the condition 1 is true;
 } else if (condition 2) {
 statements if the condition 2 is true;
 } else if (condition 3) {
 statements if the condition 3 is true;
 } . . . else {
 statements if none of the conditions are true;
 }