Windows Forms: How to make a Calculator in C#

The application built is designed to emulate the windows calculator and is done in C# .Net

Step 1Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "Calc" and then click OK

calculator in c#Step 2: Design your calculator form as below

c# calculator

Step 3: Add code to handle calculator form

using System;
using System.Windows.Forms;

namespace Calc
{
    public partial class Form1 : Form
    {
        double value;
        string coperator;
        bool check;
        public Form1()
        {
            InitializeComponent();
        }

        //Handle number button
        private void PNumber(object sender, EventArgs e)
        {
            if ((coperator == "+") || (coperator == "-") || (coperator == "*") || (coperator == "/"))
            {
                if (check)
                {
                    check = false;
                    txtResult.Text = "0";
                }
            }
            Button b = sender as Button;
            if (txtResult.Text == "0")
                txtResult.Text = b.Text;
            else
                txtResult.Text += b.Text;
        }

        //Handle operator button
        private void POperator(object sender, EventArgs e)
        {
            Button b = sender as Button;
            //Convert text to number
            value = double.Parse(txtResult.Text);
            coperator = b.Text;
            txtResult.Text += b.Text;
            check = true;
        }

        private void button20_Click(object sender, EventArgs e)
        {
            try
            {
                switch (coperator)
                {
                    case "+":
                        txtResult.Text = (value + double.Parse(txtResult.Text)).ToString();
                        break;
                    case "-":
                        txtResult.Text = (value - double.Parse(txtResult.Text)).ToString();
                        break;
                    case "*":
                        txtResult.Text = (value * double.Parse(txtResult.Text)).ToString();
                        break;
                    case "/":
                        txtResult.Text = (value / double.Parse(txtResult.Text)).ToString();
                        break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            txtResult.Text = "0";
        }

        //Clear memory
        private void button10_Click(object sender, EventArgs e)
        {
            txtResult.Text = "0";
            value = 0;
        }
    }
}

VIDEO TUTORIALS