Web Calculator C# ASP Project

Here’s another quick project displaying some simple possibilities of using C# .NET with ASP.

This is a simple web based calculator. The functionality should look pretty simple. You can perform basic math functions.

Again you can find the source code and a link to the the live example over on the C# .ASP Downloads Page.

 

Main Default.aspx Page

WebCalculatorMainPage

Default.aspx Code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.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></title>
    <style type="text/css">
        .style1
        {
            height: 30px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <asp:HiddenField ID="firstOperationField" runat="server" Value="true" />
    <asp:HiddenField ID="pendingValueField" runat="server" Value="" />
    <asp:HiddenField ID="pendingActionField" runat="server" Value="" />
    <table style="width: 100%;">
        <tr>
            <td colspan="4"><asp:TextBox ID="resultTextBox" runat="server" ReadOnly="True" Style="text-align: right"
                            Width="200px"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td class="style1">
                <asp:Button ID="clearErrorButton" runat="server" Text="CE" Width="40px" />
                <asp:Button ID="clearButton" runat="server" Text="C" Width="40px" />
                <asp:Button ID="backSpaceButton" runat="server" Text="&lt;-" Width="40px" />
                <asp:Button ID="divideButton" runat="server" Text="/" Width="40px" />
            </td>
        </tr>
        <tr>
            <td>
                <asp:Button ID="oneButton" runat="server" Text="1" Width="40px" />
                <asp:Button ID="twoButton" runat="server" Text="2" Width="40px" />
                <asp:Button ID="threeButton" runat="server" Text="3" Width="40px" />
                <asp:Button ID="mutiplyButton" runat="server" Text="*" Width="40px" />
            </td>
        </tr>
        <tr>
            <td>
                <asp:Button ID="fourButton" runat="server" Text="4" Width="40px" />
                <asp:Button ID="fiveButton" runat="server" Text="5" Width="40px" />
                <asp:Button ID="sixButton" runat="server" Text="6" Width="40px" />
                <asp:Button ID="subtractButton" runat="server" Text="-" Width="40px" />
            </td>
        </tr>
        <tr>
            <td>
                <asp:Button ID="sevenButton" runat="server" Text="7" Width="40px" />
                <asp:Button ID="eightButton" runat="server" Text="8" Width="40px" />
                <asp:Button ID="nineButton" runat="server" Text="9" Width="40px" />
                <asp:Button ID="addButton" runat="server" Text="+" Width="40px" />
            </td>
        </tr>
        <tr>
            <td>
                <asp:Button ID="signButton" runat="server" Text="+/-" Width="40px" />
                <asp:Button ID="zeroButton" runat="server" Text="0" Width="40px" />
                <asp:Button ID="pointButton" runat="server" Text="." Width="40px" />
                <asp:Button ID="equalButton" runat="server" Text="=" Width="40px" />
            </td>
        </tr>
    </table>
    <asp:Label ID="alertLabel" runat="server" Text="..." ForeColor="Red"
        Visible="False"></asp:Label>
    </form>
</body>
</html>

Default.aspx Code Behind Contents

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    //Private class variables.
    private string _currentValueString = "";
    private double _currentValueDouble = 0.0;
    private string _pendingAction = "";
    private string _pendingValueString = "";
    private double _pendingValueDouble = 0.0;
    private bool _firstOperationField = true;

    protected void Page_Load(object sender, EventArgs e)
    {
        //Resetting the alert label to not be visible.
        alertLabel.Visible = false;

        if (!IsPostBack)
        {
            //Initialize our calculator window.
            resultTextBox.Text = "0";
        }
        else
        {
            //Respond to the postback.
            //Grab the calculator window, convert and save the values as necessary
            _currentValueString = resultTextBox.Text;
            if (_currentValueString.Length > 0)
                _currentValueDouble = double.Parse(_currentValueString);    //Convert the string value to a double.

            //Save and convert the hidden field values.
            _firstOperationField = bool.Parse(firstOperationField.Value);
            _pendingAction = pendingActionField.Value;
            _pendingValueString = pendingValueField.Value;
            if (_pendingValueString.Length > 0)
                _pendingValueDouble = double.Parse(_pendingValueString);
        }

        //Add the event delegated to number buttons.
        zeroButton.Click += new EventHandler(numberButton_Click);
        oneButton.Click += new EventHandler(numberButton_Click);
        twoButton.Click += new EventHandler(numberButton_Click);
        threeButton.Click += new EventHandler(numberButton_Click);
        fourButton.Click += new EventHandler(numberButton_Click);
        fiveButton.Click += new EventHandler(numberButton_Click);
        sixButton.Click += new EventHandler(numberButton_Click);
        sevenButton.Click += new EventHandler(numberButton_Click);
        eightButton.Click += new EventHandler(numberButton_Click);
        nineButton.Click += new EventHandler(numberButton_Click);

        //Add event delegates for the action buttons.
        divideButton.Click += new EventHandler(actionButton_Click);
        mutiplyButton.Click += new EventHandler(actionButton_Click);
        subtractButton.Click += new EventHandler(actionButton_Click);
        addButton.Click += new EventHandler(actionButton_Click);
        equalButton.Click += new EventHandler(actionButton_Click);
        clearErrorButton.Click += new EventHandler(actionButton_Click);
        clearButton.Click += new EventHandler(actionButton_Click);
        backSpaceButton.Click += new EventHandler(actionButton_Click);
        signButton.Click += new EventHandler(actionButton_Click);
        pointButton.Click += new EventHandler(actionButton_Click);
    }

    void numberButton_Click(object sender, EventArgs e)
    {
        //Determine the number by extracting from the Buttons' Text Property.
        int number = Int32.Parse((sender as Button).Text);

        //Set / Append the number to the calculator window for display.
        if (_firstOperationField)
            resultTextBox.Text = number.ToString();
        else
        {
            //Prevent prepending a 0 to a number.
            if (_currentValueString == "0") _currentValueString = "";
            resultTextBox.Text = (_currentValueString + number.ToString());
        }

        //Indicate no longer first operation.
        firstOperationField.Value = "false";
    }

    void actionButton_Click(object sender, EventArgs e)
    {
        //Determine the action
        string currentAction = (sender as Button).Text;

        //Determine if there is a pending operation.
        bool pendingOperation = (_pendingValueString.Length > 0 && _currentValueString.Length > 0 &&
            _pendingAction.Length > 0);

        //Perform previous action.
        if ("/*-+=".IndexOf(currentAction) >= 0)
        {
            //Handle the arithmetic operation actions.
            if (pendingOperation)
                resultTextBox.Text = doCalculation(_pendingAction, _pendingValueDouble, _currentValueDouble).ToString();

            //Update the first operation hidden field.
            firstOperationField.Value = "true";

            //Update the previous value and action hidden fields.
            if (currentAction != "=")
            {
                //Support chaining calculation.
                pendingActionField.Value = currentAction;
                pendingValueField.Value = resultTextBox.Text;
            }
            else
            {
                pendingActionField.Value = "";
                pendingValueField.Value = "";
            }
        }
        else
        {
            //Handle the remaining actions.
            switch (currentAction)
            {
                case "C":
                    //Reset the calculator window and hidden fields.
                    resultTextBox.Text = "0";
                    pendingActionField.Value = "";
                    pendingValueField.Value = "";
                    firstOperationField.Value = "true";
                    break;
                case "CE":
                    //Clear the error.
                    resultTextBox.Text = "0";
                    firstOperationField.Value = "true";
                    break;
                case "<-":
                    //Backspace = prevent leaving "bad" data in the calculator window.
                    string newResult = _currentValueString.Substring(0, _currentValueString.Length - 1);
                    if (newResult.Length == 0 || newResult == "")
                        resultTextBox.Text = "0";
                    else
                        resultTextBox.Text = newResult;
                    break;
                case ".":
                    //For the decimal point.
                    if (_currentValueString.IndexOf(".") < 0)
                        resultTextBox.Text = _currentValueString + ".";
                    break;
                case "+/-":
                    resultTextBox.Text = (_currentValueDouble * -1).ToString();
                    break;
            }
        }
    }

    private double doCalculation(string action, double left, double right)
    {
        //Perform the arithmetic calculations.
        double result = 0.0;
        switch (action)
        {
            case "/":
                //Prevent dividing by zero.
                if (right != 0)
                    result = left / right;
                else
                {
                    //Alert the user if trying to divide by zero.
                    alertLabel.Text = "Error: Cannot Divide By Zero";
                    alertLabel.Visible = true;
                }
                break;
            case "*":
                result = left * right;
                break;
            case "-":
                result = left - right;
                break;
            case "+":
                result = left + right;
                break;
        }
        return result;
    }
}
Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s