In this tutorial you will learn how to make a Windows Form Calculator in C# using Visual Studio 2017
Here is output:
List of Components Names:
Label: lbResult
TextBox: txtResult
Buttons: b0, b1, b2 …….b9, bAdd, bSub, bDiv, bMul, bEq, bCE, bC and button15 (“,”)
Code: Basic Calculator Using Windows Forms
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 | public partial class Form1 : Form { bool operandPerformed = false; string operand = ""; double result = 0; public Form1() { InitializeComponent(); } private void NumEvent(object sender, EventArgs e) { if (txtResult.Text == "0" || operandPerformed) txtResult.Clear(); Button btn = (Button)sender; txtResult.Text += btn.Text; operandPerformed = false; } private void OperandEvent(object sender, EventArgs e) { operandPerformed = true; Button btn = (Button)sender; string newOperand = btn.Text; lbResult.Text = lbResult.Text + " " + txtResult.Text + " " + newOperand; switch(operand) { case "+":txtResult.Text = (result + Double.Parse(txtResult.Text)).ToString();break; case "-": txtResult.Text = (result - Double.Parse(txtResult.Text)).ToString(); break; case "*": txtResult.Text = (result * Double.Parse(txtResult.Text)).ToString(); break; case "/": txtResult.Text = (result / Double.Parse(txtResult.Text)).ToString(); break; default:break; } result = Double.Parse(txtResult.Text); operand = newOperand; } private void bCE_Click(object sender, EventArgs e) { txtResult.Text = "0"; } private void bC_Click(object sender, EventArgs e) { txtResult.Text = "0"; lbResult.Text = ""; result = 0; operand = ""; } private void bEq_Click(object sender, EventArgs e) { lbResult.Text = ""; operandPerformed = true; switch(operand) { case "+": txtResult.Text = (result + Double.Parse(txtResult.Text)).ToString(); break; case "-": txtResult.Text = (result - Double.Parse(txtResult.Text)).ToString(); break; case "*": txtResult.Text = (result * Double.Parse(txtResult.Text)).ToString(); break; case "/": txtResult.Text = (result / Double.Parse(txtResult.Text)).ToString(); break; default: break; } result = Double.Parse(txtResult.Text); txtResult.Text = result.ToString(); result = 0; operand = ""; } private void button15_Click(object sender, EventArgs e) { if(!operandPerformed && !txtResult.Text.Contains(",")) { txtResult.Text += ","; } else if(operandPerformed) { txtResult.Text = "0"; } if(!txtResult.Text.Contains(",")) { txtResult.Text += ","; } operandPerformed = false; } } |