Simple Web Based Calculator

In this we will create simple calculator that is able to add, subtract, multiply, and divide values.

Add following controls to your page, set their ID and other properties as in the following table and arrange the control as shown in figure 1.2

Table

tableControl.png

figure 1.2

calcpage.png

Double click the Calculate button and add the following code to click event of button.

    protected void Button1_Click(object sender, EventArgs e)

    {

        if (TextBox1.Text.Length > 0 && TextBox2.Text.Length > 0)

        {

            double res = 0;

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

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

            switch (OperatorList.SelectedValue)

            {

                case "+":

                    res = value1 + value2;

                    break;

                case "-":

                    res = value1 - value2;

                    break;

                case "*":

                    res = value1 * value2;

                    break;

                case "/":

                    res = value1 / value2;

                    break;

            }

            LblResult.Text = res.ToString();

        }

        else

            LblResult.Text = string.Empty;

    }

Save all the changes and press ctrl+F5 to open the web page in browser.

Go ahead and  enter the number in first and second textbox.

Choose the operator from drop-down list, and click calculate button. you will see lable is updated with result