Home

Conditional Switches

 

if Switches

 

The Ternary Operator (?:)

The ternary conditional operator behaves like an if…else statement. Its syntax is:

Condition ? Statement1 : Statement2;

The Condition is tested first. If the Condition is true, then Statement1 executes. If the Condition is false, then Statement2 executes. 

 Here is an example:

<%@ Page Language="C#" %>
<html>
<head>

<script runat="server">

private void btnCopmpareClick(object sender, EventArgs e)
{
    double Number1 = 0.00;
    double Number2 = 0.00;
    double Maximum = 0.00;

    Number1 = double.Parse(txtNumber1.Text);
    Number2 = double.Parse(txtNumber2.Text);

    Maximum = (Number1 < Number2) ? Number2 : Number1;

    lblMessage.Text = "The maximum of " + Number1.ToString() +
		      " and " + Number2.ToString() + 
		      " is " + Maximum.ToString();
}
</script>

<title>Altair Real Estate</title>
</head>
<body>

<form id="frmExercise" runat="server">
  <table>
    <tr>
      <td>Enter a first number:</td>
      <td><asp:TextBox id="txtNumber1" runat="server" /></td>
    </tr>
    <tr>
      <td>Enter a second number:</td>
      <td><asp:TextBox id="txtNumber2" runat="server" /></td>
    </tr>
    <tr>
      <td colspan="2" align="right">
        <asp:Button id="btnCompare"
		    Text="Compare"
		    OnClick="btnCopmpareClick"
		    runat="server" /></td>
    </tr>
    <tr>
      <td colspan="2">
	<asp:Label id="lblMessage" runat="server" /></td>
    </tr>
  </table>
</form>

</body>
</html>

Here is an example of testing the code:

Ternary

Practical LearningPractical Learning: Introducing Conditional Switches

  1. Start Microsoft Visual Studio or Microsoft Visual Web Developer
  2. Start creating a web site
  3. Set the language to Visual C# et set the site name to timesheet2
  4. Click OK
  5. In the Solution Explorer, right-click Default.aspx and click Rename
  6. Type index.aspx and press Enter
  7. Click the Source button and change the file as follows:
     
    <%@ Page Language="C#"
             AutoEventWireup="true"  
             CodeFile="index.aspx.cs" 
             Inherits="_Default" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <title>Time Sheet</title>
      
    </head>
    <body>
    <form id="frmTimeSheet" runat="server">
    <div>
    
    <table style="width: 500px">
      <tr>
        <td style="width:90px">Employee #:</td>
        <td style="width:20px">
          <asp:TextBox ID="txtEmployeeNumber"
                       Columns="10" runat="server"></asp:TextBox>
          </td>
        <td style="width:50px; text-align: center">
            <asp:Button ID="btnFind" runat="server" Text="Find" />
        </td>
        <td>
          <asp:TextBox ID="txtEmployeeName"
                       Width="215px" runat="server"></asp:TextBox>
        </td>
            </tr>
            </table>
    
    &nbsp;
    
    <table border="0" width="600">
      <tr>
        <td style="width:90px"></td>
        <td align="center">Monday</td>
        <td align="center">Tuesday</td>
        <td align="center">Wednesday</td>
        <td align="center">Thursday</td>
        <td align="center">Friday</td>
        <td align="center">Saturday</td>
        <td align="center">Sunday</td>
      </tr>
      <tr>
        <td>Week 1:</td>
        <td align="center">
            <asp:TextBox ID="txtWeek1Monday"
                         runat="server"
                         Columns="5">0.00</asp:TextBox>
          </td>
        <td align="center">
            <asp:TextBox ID="txtWeek1Tuesday"
                         Columns="5" runat="server">0.00</asp:TextBox>
          </td>
        <td align="center">
            <asp:TextBox ID="txtWeek1Wednesday"
                         Columns="5" runat="server">0.00</asp:TextBox>
          </td>
        <td align="center">
            <asp:TextBox ID="txtWeek1Thursday"
                         Columns="5" runat="server">0.00</asp:TextBox>
          </td>
        <td align="center">
            <asp:TextBox ID="txtWeek1Friday"
                         Columns="5" runat="server">0.00</asp:TextBox>
          </td>
        <td align="center">
            <asp:TextBox ID="txtWeek1Saturday"
                         Columns="5" runat="server">0.00</asp:TextBox>
          </td>
        <td align="center">
            <asp:TextBox ID="txtWeek1Sunday"
                         Columns="5" runat="server">0.00</asp:TextBox>
          </td>
      </tr>
      <tr>
        <td>Week 2:</td>
        <td align="center">
            <asp:TextBox ID="txtWeek2Monday"
                         Columns="5" runat="server">0.00</asp:TextBox>
          </td>
        <td align="center">
            <asp:TextBox ID="txtWeek2Tuesday"
                         Columns="5" runat="server">0.00</asp:TextBox>
          </td>
        <td align="center">
            <asp:TextBox ID="txtWeek2Wednesday"
                         Columns="5" runat="server">0.00</asp:TextBox>
          </td>
        <td align="center">
            <asp:TextBox ID="txtWeek2Thursday"
                         Columns="5" runat="server">0.00</asp:TextBox>
          </td>
        <td align="center">
            <asp:TextBox ID="txtWeek2Friday"
                         Columns="5" runat="server">0.00</asp:TextBox>
          </td>
        <td align="center">
            <asp:TextBox ID="txtWeek2Saturday"
                         Columns="5" runat="server">0.00</asp:TextBox>
          </td>
        <td align="center">
            <asp:TextBox ID="txtWeek2Sunday"
                         Columns="5" runat="server">0.00</asp:TextBox>
          </td>
      </tr>
    </table>
    
    &nbsp;
    
    <table width="600">
      <tr>
        <td align="center">
            <asp:Button ID="btnEvaluate" Width="200"
                        Text="Evaluate Time Sheet" runat="server" />
        </td>
      </tr>
    </table>
    
    &nbsp;
    
    <table border="0" style="width:450px">
      <tr>
        <td style="width:350px;"></td>
        <td align="center">Regular Time</td>
        <td align="center">Overtime</td>
      </tr>
      <tr>
        <td align="right">Week 1</td>
        <td width="33%" align="center">
            <asp:TextBox ID="txtWeek1RegularTime"
                         Columns="10" runat="server">0.00</asp:TextBox>
          </td>
        <td width="34%" align="center">
            <asp:TextBox ID="txtWeek1Overtime"
                         Columns="10" runat="server">0.00</asp:TextBox>
          </td>
      </tr>
      <tr>
        <td align="right">Week 2</td>
        <td width="33%" align="center">
            <asp:TextBox ID="txtWeek2RegularTime"
                         Columns="10" runat="server">0.00</asp:TextBox>
          </td>
        <td width="34%" align="center">
            <asp:TextBox ID="txtWeek2Overtime"
                         Columns="10" runat="server">0.00</asp:TextBox>
          </td>
      </tr>
    </table>
        
    </div>
    </form>
    </body>
    </html>
  8. Save the file and click the Design button

    Time Sheet

  9. Double-click the Evaluate and implement the event as follows:
     
    protected void btnEvaluate_Click(object sender, EventArgs e)
    {
            double Week1Monday, Week1Tuesday, Week1Wednesday,
                   Week1Thursday, Week1Friday, Week1Saturday, Week1Sunday;
            double Week2Monday, Week2Tuesday, Week2Wednesday,
                   Week2Thursday, Week2Friday, Week2Saturday, Week2Sunday;
            double Week1RegularTime, Week1Overtime,
                   Week2RegularTime, Week2Overtime;
            double Week1Total, Week2Total;
    
            Week1Monday = double.Parse(txtWeek1Monday.Text);
            Week1Tuesday = double.Parse(txtWeek1Tuesday.Text);
            Week1Wednesday = double.Parse(txtWeek1Wednesday.Text);
            Week1Thursday = double.Parse(txtWeek1Thursday.Text);
            Week1Friday = double.Parse(txtWeek1Friday.Text);
            Week1Saturday = double.Parse(txtWeek1Saturday.Text);
            Week1Sunday = double.Parse(txtWeek1Sunday.Text);
    
            Week2Monday = double.Parse(txtWeek2Monday.Text);
            Week2Tuesday = double.Parse(txtWeek2Tuesday.Text);
            Week2Wednesday = double.Parse(txtWeek2Wednesday.Text);
            Week2Thursday = double.Parse(txtWeek2Thursday.Text);
            Week2Friday = double.Parse(txtWeek2Friday.Text);
            Week2Saturday = double.Parse(txtWeek2Saturday.Text);
            Week2Sunday = double.Parse(txtWeek2Sunday.Text);
    
            Week1Total = Week1Monday + Week1Tuesday + Week1Wednesday +
                         Week1Thursday + Week1Friday +
                         Week1Saturday + Week1Sunday;
    
            if( Week1Total < 40 )
            {
                Week1RegularTime = Week1Total;
                Week1Overtime = 0;
            }
            else
            {
                Week1RegularTime = 40;
                Week1Overtime = Week1Total - Week1RegularTime;
            }
    
            Week2Total = Week2Monday + Week2Tuesday + Week2Wednesday +
                         Week2Thursday + Week2Friday +
                         Week2Saturday + Week2Sunday;
    
            if( Week2Total < 40 )
            {
                Week2RegularTime = Week2Total;
                Week2Overtime = 0;
            }
            else
            {
                Week2RegularTime = 40;
                Week2Overtime = Week2Total - Week2RegularTime;
            }
    
            txtWeek1Monday.Text = Week1Monday.ToString("F");
            txtWeek1Tuesday.Text = Week1Tuesday.ToString("F");
            txtWeek1Wednesday.Text = Week1Wednesday.ToString("F");
            txtWeek1Thursday.Text = Week1Thursday.ToString("F");
            txtWeek1Friday.Text = Week1Friday.ToString("F");
            txtWeek1Saturday.Text = Week1Saturday.ToString("F");
            txtWeek1Sunday.Text = Week1Sunday.ToString("F");
    
            txtWeek2Monday.Text = Week2Monday.ToString("F");
            txtWeek2Tuesday.Text = Week2Tuesday.ToString("F");
            txtWeek2Wednesday.Text = Week2Wednesday.ToString("F");
            txtWeek2Thursday.Text = Week2Thursday.ToString("F");
            txtWeek2Friday.Text = Week2Friday.ToString("F");
            txtWeek2Saturday.Text = Week2Saturday.ToString("F");
            txtWeek2Sunday.Text = Week2Sunday.ToString("F");
    
            txtWeek1RegularTime.Text = Week1RegularTime.ToString("F");
            txtWeek1Overtime.Text = Week1Overtime.ToString("F");
            txtWeek2RegularTime.Text = Week2RegularTime.ToString("F");
            txtWeek2Overtime.Text = Week2Overtime.ToString("F");
        }
    }
  10. Click the index.aspx tab to return to the form

if…else if and if…else if…else

If you want to test two conditions with two different outcomes, you can use an if...else if condition. Its formula is:

if(Condition1) Statement1;
else if(Condition2) Statement2;

Condition1 would be checked first. If Condition1 is true, then Statement1 would execute. If Condition1 is false, then Condition2 is checked. If Condition2 is true, then Statement2 executes. Any other result would be ignored. Here is an example:

<%@ Page Language="C#" %>
<html>
<head>

<script runat="server">
private void btnValidateClick(object sender, EventArgs e)
{
    if( TypesOfHouses.SelectedIndex == 0 )
	lblDescription.Text = "We have many low-level and high rise " +
		"buildings featuring the best condos in the area.";
    else if( TypesOfHouses.SelectedIndex == 1 )
	lblDescription.Text = "Our townhouses are the widest " +
		"you can find with various levels and rooms.";
}
</script>

<title>Altair Real Estate</title>
</head>
<body>

<h3>Altair Real Estate</h3>

<form id="frmRealEstate" runat="server">
  <table>
    <tr>
      <td>What type of property do you want to purchase?</td>
      <td>
	<asp:DropDownList id="TypesOfHouses" runat="server">
    	  <asp:ListItem>condominium</asp:ListItem>
    	  <asp:ListItem>townhouse</asp:ListItem>
    	  <asp:ListItem>single family</asp:ListItem>
  	</asp:DropDownList>
      </td>
    </tr>
    <tr>
      <td></td>
      <td align="center">
	<asp:Button id="btnValidate"
		    Text="Validate"
		    OnClick="btnValidateClick"
		    runat="server"></asp:Button>
      </td>
    </tr>
    <tr>
      <td colspan="2">
	<asp:Label id="lblDescription" runat="server"></asp:Label>
      </td>
    </tr>
</form>

</body>
</html>

Here is an example of testing the web page:

Real Estate

Here is another example of testing the page:

Real Estate

Notice that only two conditions are evaluated. Any condition other than these two is not considered. Because there can be other alternatives, you can use one of the following formulas:

if(Condition1)
    Statement1;
else if(Condition2)
    Statement2;
else
    Statement-n;
if(Condition1)
    Statement1;
else if(Condition2)
    Statement2;
else if(Condition3)
    Statement3;
else
    Statement-n;

The first condition, Condition1, is checked. If that condition is true, Statement1 executes. If Condition1 is false, then the second condition, Condition2 is checked. If Condition2 is true, Statement2 executes. When a Condition-n is true, its corresponding statement executes. This means that you can include as many conditions as you see fit using the else if statement. If after examining all the known possible conditions you still think that there might be an unexpected condition, you can use the optional single else. Here is an example:

<%@ Page Language="C#" %>
<html>
<head>

<script runat="server">
private void HouseSelected(object sender, EventArgs e)
{
    if( TypesOfHouses.SelectedIndex == 0 )
	lblDescription.Text = "We have many low-level and high rise " +
		"buildings featuring the best condos in the area.";
    else if( TypesOfHouses.SelectedIndex == 1 )
	lblDescription.Text = "Our townhouses are the widest " +
		"you can find with various levels and rooms.";
    else if( TypesOfHouses.SelectedIndex == 2 )
	lblDescription.Text = "We have many single family houses in " +
		"ontemporary, classical, victorian architecture.";
    else
	lblDescription.Text = "We will try to assist you in making " +
		"a clear choice for your new house";
}
</script>

<title>Altair Real Estate</title>
</head>
<body>

<h3>Altair Real Estate</h3>

<form id="frmRealEstate" runat="server">
  <table>
    <tr>
      <td>What type of property do you want to purchase?</td>
      <td>
	<asp:DropDownList id="TypesOfHouses"
			  AutoPostBack="True"
     OnSelectedIndexChanged="HouseSelected" runat="server">
    	  <asp:ListItem>Condominium</asp:ListItem>
    	  <asp:ListItem>Townhouse</asp:ListItem>
    	  <asp:ListItem>Single Family</asp:ListItem>
    	  <asp:ListItem>Unknown</asp:ListItem>
  	</asp:DropDownList>
      </td>
    </tr>
    <tr>
      <td colspan="2">
	<asp:Label id="lblDescription" runat="server"></asp:Label>
      </td>
    </tr>
</form>

</body>
</html>

Here is an example of testing the page:

Real Estate

Here is another test of the page:

Real Estate

Practical LearningPractical Learning: Using if…else if and if…else if…else

  1. Double-click the top button on the form and implement its event as follows:
     
    protected void btnFind_Click(object sender, EventArgs e)
    {
            if (txtEmployeeNumber.Text.Equals("22-804"))
                txtEmployeeName.Text = "Helene Mukoko";
            else if (txtEmployeeNumber.Text.Equals("92-746"))
                txtEmployeeName.Text = "Raymond Kouma";
            else if (txtEmployeeNumber.Text.Equals("54-080"))
                txtEmployeeName.Text = "Henry Larson";
            else if (txtEmployeeNumber.Text.Equals("86-285"))
                txtEmployeeName.Text = "Gertrude Monay";
            else if (txtEmployeeNumber.Text.Equals("20-860"))
                txtEmployeeName.Text = "Paul Bertrand Yamaguchi";
            else
                txtEmployeeName.Text = "Unidentified Employee";
    }
  2. Press Ctrl + F5 to execute the application
  3. Click the top text box, type 92-746 and click the top button
 
 
 
 

Case Switches

 

Introduction

When defining an expression whose result would lead to a specific program execution, the switch statement considers that result and executes a statement based on the possible outcome of that expression, this possible outcome is called a case. The different outcomes are listed in the body of the switch statement and each case has its own execution, if necessary. The body of a switch statement is delimited from an opening to a closing curly brackets: “{“ to “}”. The syntax of the switch statement is:

switch(Expression)
{
    case Choice1:
         Statement1;
	break;
    case Choice2:
         Statement2;
	break;
    case Choice-n:
         Statement-n;
	break;
}

The expression to examine in a case statement is an integer. Since a member of an enumeration (enum) and the character (char) data types are just other forms of integers, they can be used too. Here is an example of using the switch statement:

<%@ Page Language="C#" %>
<html>
<head>

<script runat="server">
private void HouseSelected(object sender, EventArgs e)
{
    switch(TypesOfHouses.SelectedIndex)
    {
    case 0:
	lblDescription.Text = "We have many low-level and high rise " +
		"buildings featuring the best condos in the area.";
	break;

    case 1:
	lblDescription.Text = "Our townhouses are the widest " +
		"you can find with various levels and rooms.";
	break;

    case 2:
	lblDescription.Text = "We have many single family houses in " +
		"ontemporary, classical, victorian architecture.";
	break;
    }
}
</script>

<title>Altair Real Estate</title>
</head>
<body>

<h3>Altair Real Estate</h3>

<form id="frmRealEstate" runat="server">
  <table>
    <tr>
      <td>What type of property do you want to purchase?</td>
      <td>
	<asp:DropDownList id="TypesOfHouses"
			  AutoPostBack="True"
     OnSelectedIndexChanged="HouseSelected" runat="server">
    	  <asp:ListItem>Condominium</asp:ListItem>
    	  <asp:ListItem>Townhouse</asp:ListItem>
    	  <asp:ListItem>Single Family</asp:ListItem>
    	  <asp:ListItem>Unknown</asp:ListItem>
  	</asp:DropDownList>
      </td>
    </tr>
    <tr>
      <td colspan="2">
	<asp:Label id="lblDescription" runat="server"></asp:Label>
      </td>
    </tr>
</form>

</body>
</html>

When establishing the possible outcomes that the switch statement should consider, at times there will be possibilities other than those listed and you will be likely to consider them. This special case is handled by the default keyword. The default case would be considered if none of the listed cases matches the supplied answer. The syntax of the switch statement that considers the default case would be:

switch(Expression)
{
    case Choice1:
         Statement1;
	break;
    case Choice2:
         Statement2;
	break;
    case Choice-n:
         Statement-n;
	break;
    default:
         Other-Possibility;
	break;
}

Therefore another version of the program above would be

<script runat="server">
private void HouseSelected(object sender, EventArgs e)
{
    switch(TypesOfHouses.SelectedIndex)
    {
    case 0:
	lblDescription.Text = "We have many low-level and high rise " +
		"buildings featuring the best condos in the area.";
	break;

    case 1:
	lblDescription.Text = "Our townhouses are the widest " +
		"you can find with various levels and rooms.";
	break;

    case 2:
	lblDescription.Text = "We have many single family houses in " +
		"ontemporary, classical, victorian architecture.";
	break;

    default:
	lblDescription.Text = "We will try to assist you in making " +
		"a clear choice for your new house";
	break;
    }
}
</script>

Besides a value of an int type, you can also use another variant of integers on a switch statement. For example, you can use letters to validate the cases.

Combining Cases

Each of the cases we have used so far examined only one possibility before executing the corresponding statement. You can combine cases to execute the same statement. To do this, type a case, its value, and the semi-colon. Type another case using the same formula. When the cases are ready, you can then execute the desired statement. Here is an example:

<script runat="server">
private void HouseSelected(object sender, EventArgs e)
{
    switch(TypesOfHouses.SelectedIndex)
    {
    case 0:
	lblDescription.Text = "We have many low-level and high rise " +
		"buildings featuring the best condos in the area.";
	break;

    case 1:
    case 2:
	lblDescription.Text = "Our homes are built by the most " +
		"honest builders in the area.";
	break;

	lblDescription.Text = "We have many single family houses in " +
		"ontemporary, classical, victorian architecture.";
	break;

    default:
	lblDescription.Text = "We will try to assist you in making " +
		"a clear choice for your new house";
	break;

    }
}
</script>

Using Enumerations

One of the most fundamental uses of enumerations is to process them in a switch statement. To do this, you pass the value of an enumeration to a switch. The values of the enumerations are then processed in the case statements.

 
 
   
 

Previous Copyright © 2009 FunctionX Next