Creating a Calculator | Rewritten in C#

using System;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
string oper;
string num1, num2 = null;
public Form1()
{
InitializeComponent();
}

private void Button1_Click(object sender, EventArgs e)
{
TextBox1.AppendText("1");
}
private void Button2_Click(object sender, EventArgs e)
{
TextBox1.AppendText("2");
}
private void Button3_Click(object sender, EventArgs e)
{
TextBox1.AppendText("3");
}
private void Button4_Click(object sender, EventArgs e)
{
TextBox1.AppendText("4");
}
private void Button5_Click(object sender, EventArgs e)
{
TextBox1.AppendText("5");
}
private void Button6_Click(object sender, EventArgs e)
{
TextBox1.AppendText("6");
}
private void Button7_Click(object sender, EventArgs e)
{
TextBox1.AppendText("7");
}
private void Button8_Click(object sender, EventArgs e)
{
TextBox1.AppendText("8");
}
private void Button9_Click(object sender, EventArgs e)
{
TextBox1.AppendText("9");
}
private void btnZero_Click(object sender, EventArgs e)
{
TextBox1.AppendText("0");
}
private void btnEquals_Click(object sender, EventArgs e)
{
if (oper == null)
{
MessageBox.Show("You must enter a second number");
return;
}
num2 = TextBox1.Text;
TextBox1.Text = Convert.ToString(calculateit(Convert.ToDouble(num1), Convert.ToDouble(num2), oper));
}
private void btnAdd_Click(object sender, EventArgs e)
{
if (num1 == null)
{
num1 = TextBox1.Text;
oper = "+";
TextBox1.Clear();
}
else
{
num1 = Convert.ToString(calculateit(Convert.ToDouble(num1), Convert.ToDouble(num2), oper));
oper = "+";
TextBox1.Clear();
}
}
private void btnMinus_Click(object sender, EventArgs e)
{
if (num1 == null)
{
num1 = TextBox1.Text;
}
else
{
num1 = Convert.ToString(calculateit(Convert.ToDouble(num1), Convert.ToDouble(num2), oper));
oper = "-";
TextBox1.Clear();
}
}
private void btnMultiply_Click(object sender, EventArgs e)
{
if (num1 == null)
{
num1 = TextBox1.Text;
}
else
{
num1 = Convert.ToString(calculateit(Convert.ToDouble(num1), Convert.ToDouble(num2), oper));
oper = "*";
TextBox1.Clear();
}
}
private void btnDivide_Click(object sender, EventArgs e)
{
if (num1 == null)
{
num1 = TextBox1.Text;
}
else
{
num1 = Convert.ToString(calculateit(Convert.ToDouble(num1), Convert.ToDouble(num2), oper));
oper = "/";
TextBox1.Clear();
}
}
private void btnClear_Click(object sender, EventArgs e)
{

}
public virtual double calculateit(double n1, double n2, string op)
{
switch (op)
{
case "+":
return n1 + n2;
case "-":
return n1 - n2;
case "*":
return n1 * n2;
case "/":
return n1 / n2;
}
return 0;
}

}
}

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.