Creating a Simple Web-Based Calculator with ASP.NET 4

Creating a Simple Web-Based Calculator with ASP.NET 4

Beginning ASP.NET 4 bookIn this exercise you create a simple calculator that is able to add, subtract, multiply, and divide values. It shows you how to use some of the logical and assignment operators and demonstrates the If and Select Case / switch constructs.

1. Start by creating a new Web Form called CalculatorDemo.aspx in the Demos folder. Make sure you don’t name the page Calculator or you’ll run into troubles later in this chapter where you create a class by that name. Once again, make sure you’re using the Code Behind model and select the correct programming language.

2. Switch the page to Design View, and click in the dashed rectangle to put the focus on it. Choose Table Ø Insert Table from the main menu and add a table with three rows and three columns. Merge all three cells of the first row by selecting them, right-clicking the selection, and choosing Modify Ø Merge Cells from the menu that appears.

3. Add the following controls to the page, set their ID and other properties as in the following table, and arrange the controls as shown in Figure 5-3. 

Control Type
Control ID
Property Settings
Label
ResultLabel
Clear its Text property. To do this, right-click the property name in the Properties Grid and choose Reset.
TextBox
ValueBox1
 
DropDownList
OperatorList
Add four ListItems for the following arithmetic operators using the DropDownList’s Smart Tasks panel.
+
-
*
/
TextBox
ValueBox2
 
Button
CalculateButton
Set the Text property of the button to Calculate.

When you’re done, your page should look like Figure 5-3 in Design View.

ASP.NET calculator example

Figure 5-3

4. Double-click the Calculate button and add the following bolded code in the code placeholder that VWD added for you:

VB.NET

Protected Sub CalculateButton_Click(ByVal sender As Object,

         ByVal e As System.EventArgs) Handles CalculateButton.Click

  If ValueBox1.Text.Length > 0 AndAlso ValueBox2.Text.Length > 0 Then

 

    Dim result As Double = 0

    Dim value1 As Double = Convert.ToDouble(ValueBox1.Text)

    Dim value2 As Double = Convert.ToDouble(ValueBox2.Text)

 

    Select Case OperatorList.SelectedValue

      Case "+"

        result = value1 + value2

      Case "-"

        result = value1 – value2

      Case "*"

        result = value1 * value2

      Case "/"

        result = value1 / value2

    End Select

    ResultLabel.Text = result.ToString()

  Else

    ResultLabel.Text = String.Empty

  End If

End Sub

C#

protected void CalculateButton_Click(object sender, EventArgs e)

{

  if (ValueBox1.Text.Length > 0 && ValueBox2.Text.Length > 0)

  {

    double result = 0;

    double value1 = Convert.ToDouble(ValueBox1.Text);

    double value2 = Convert.ToDouble(ValueBox2.Text);

 

    switch (OperatorList.SelectedValue)

    {

      case "+":

        result = value1 + value2;

        break;

      case "-":

        result = value1 – value2;

        break;

      case "*":

        result = value1 * value2;

        break;

      case "/":

        result = value1 / value2;

        break;

    }

    ResultLabel.Text = result.ToString();

  }

  else

  {

    ResultLabel.Text = string.Empty;

  }

}

5. Save all changes and press Ctrl+F5 to open the page in the browser. If you get an error instead of seeing the page, make sure you typed the code exactly as shown here, and that you named all controls according to the table you saw earlier.

6. Enter a number in the first and second text boxes, choose an operator from the drop-down list, and click the Calculate button. The code in the Code Behind fires and then — based on the item you selected in the drop-down list — the correct calculation is performed and the label is updated with the result.

7. Go ahead and try some other numbers and operators; you’ll see that the calculator carries out the right operation every time you click the Calculate button.

How It Works

When you enter two values and click the Calculate button, the following code in the Code Behind fires:

VB.NET

If ValueBox1.Text.Length > 0 AndAlso ValueBox2.Text.Length > 0 Then

C#

if (ValueBox1.Text.Length > 0 && ValueBox2.Text.Length > 0)

This code is necessary to ensure that both text boxes contain a value. (In Chapter 9 you see a much cleaner way to perform this validation.) The code uses a simple If statement to ensure that both fields have a value. It also uses AndAlso or && to avoid checking the Text property of the second TextBox when the first is empty.

The code then declares a Double to hold the result of the calculation and then gets the values from the two text box controls, converts the values to a Double using the ToDouble method of the Convert class, and then sets up a Select Case (switch in C#) block to handle the type of operator you have chosen in the drop-down list:

VB.NET

Select Case OperatorList.SelectedValue

  Case "+"

  result = value1 + value2

C#

switch (OperatorList.SelectedValue)

{

  case "+":

    result = value1 + value2;

    break;

For each item in the drop-down list, there is a case statement. When you have chosen the + operator from the list, the code in the first case block will fire, and result is assigned the sum of the numbers you entered in the two text boxes. Likewise, when you choose the subtraction operator, for example, the two values are subtracted from each other.

At the end, the result is converted to a String and then displayed on the label called ResultLabel.

The Select Case / switch statements close off the discussion about making decisions in your code. There’s one more group of statements left: Loops that enable you to loop over code or over objects in a collection.

   This article is excerpted from chapter 5 "Programming Your ASP.NET Web Pages" of the book Beginning ASP.NET 4: in C# and VB by Imar Spaanjaars (ISBN: 978-0-470-50221-1, Wrox, 2010, Copyright Wiley Publishing Inc.)

Tags:

Comments

2 Responses to “Creating a Simple Web-Based Calculator with ASP.NET 4”

  1. Anonymous says:

    thanx yarrrrrrrrrrrrrrrrrrrrrrrrrrr

  2. Anonymous says:

    It’s very nice but how to upload on website this calculator plz help me
    ravifichadia2011@gmail.com

Leave a Reply

What is 14 + 10 ?
Please leave these two fields as-is:
IMPORTANT! To be able to proceed, you need to solve the following simple math (so we know that you are a human) :-)