C# language, Calculator - c#

Hello everyone and thanks for helping me.
I made this calculator in C# and i got one problem.
When i add something like 5+5+5 it gives me correct result but when i want to substract more than two number and also divide or multiply more than two number i don't get correct result.
Do you know what i am doing wrong,
Thank you very much!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace calculator
{
public partial class Calculator : Form
{
public Calculator()
{
InitializeComponent();
}
private void btnOne_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnOne.Text;
//txtDisplay.Text = btnOne.Text;
}
private void btnTwo_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnTwo.Text;
}
private void btnThree_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnThree.Text;
}
private void btnFour_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnFour.Text;
}
private void btnFive_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnFive.Text;
}
private void btnSix_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnSix.Text;
}
private void btnSeven_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnSeven.Text;
}
private void btnEight_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnEight.Text;
}
private void btnNine_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnNine.Text;
}
private void btnZero_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnZero.Text;
}
private void btnClear_Click(object sender, EventArgs e)
{
txtDisplay.Clear();
}
private void btnPoint_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + ",";
}
double total1 = 0;
double total2 = 0;
bool plusButtonClicked = false;
bool minusButtonClicked = false;
bool divideButtonClicked = false;
bool multiplyButtonClicked = false;
private void btnPlus_Click(object sender, EventArgs e)
{
plusButtonClicked = true;
minusButtonClicked = false;
divideButtonClicked = false;
multiplyButtonClicked = false;
total1 = total1 + double.Parse(txtDisplay.Text);
txtDisplay.Clear();
}
private void btnMinus_Click(object sender, EventArgs e)
{
plusButtonClicked = false;
minusButtonClicked = true;
divideButtonClicked = false;
multiplyButtonClicked = false;
total1 = total1 + double.Parse(txtDisplay.Text);
txtDisplay.Clear();
}
private void btnDivide_Click(object sender, EventArgs e)
{
total1 = total1 + double.Parse(txtDisplay.Text);
txtDisplay.Clear();
plusButtonClicked = false;
minusButtonClicked = false;
divideButtonClicked = true;
multiplyButtonClicked = false;
}
private void btnMultiply_Click(object sender, EventArgs e)
{
total1 = total1 + double.Parse(txtDisplay.Text);
txtDisplay.Clear();
plusButtonClicked = false;
minusButtonClicked = false;
divideButtonClicked = false;
multiplyButtonClicked = true;
}
private void btnEquals_Click(object sender, EventArgs e)
{
if (plusButtonClicked == true)
{
total2 = total1 + double.Parse(txtDisplay.Text);
}
else if (minusButtonClicked == true)
{
total2 = total1 - double.Parse(txtDisplay.Text);
}
else if (divideButtonClicked == true)
{
total2 = total1 / double.Parse(txtDisplay.Text);
}
else if (multiplyButtonClicked == true)
{
total2 = total1 * double.Parse(txtDisplay.Text);
}
txtDisplay.Text = total2.ToString();
total1 = 0;
}
}
}

This code is has not been thoroughly tested. Why don't you try something like the following:
using System;
using System.Windows.Forms;
namespace Calculator
{
public enum Operator
{
None,
Add,
Minus,
Divide,
Multiply
}
public partial class Calculator : Form
{
private double total = 0;
private double currentValue = 0;
private Operator currentOperator;
public Calculator()
{
InitializeComponent();
}
private void btnOne_Click(object sender, EventArgs e)
{
ShowInput(btnOne.Text);
}
private void btnTwo_Click(object sender, EventArgs e)
{
ShowInput(btnTwo.Text);
}
private void btnThree_Click(object sender, EventArgs e)
{
ShowInput(btnThree.Text);
}
private void btnFour_Click(object sender, EventArgs e)
{
ShowInput(btnFour.Text);
}
private void btnFive_Click(object sender, EventArgs e)
{
ShowInput(btnFive.Text);
}
private void btnSix_Click(object sender, EventArgs e)
{
ShowInput(btnSix.Text);
}
private void btnSeven_Click(object sender, EventArgs e)
{
ShowInput(btnSeven.Text);
}
private void btnEight_Click(object sender, EventArgs e)
{
ShowInput(btnEight.Text);
}
private void btnNine_Click(object sender, EventArgs e)
{
ShowInput(btnNine.Text);
}
private void btnZero_Click(object sender, EventArgs e)
{
ShowInput(btnZero.Text);
}
private void btnClear_Click(object sender, EventArgs e)
{
currentOperator = Operator.None;
txtDisplay.Clear();
total = 0;
}
private void btnPoint_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + '.';
}
private void btnPlus_Click(object sender, EventArgs e)
{
ApplyOperator(Operator.Add);
}
private void btnMinus_Click(object sender, EventArgs e)
{
ApplyOperator(Operator.Minus);
}
private void btnDivide_Click(object sender, EventArgs e)
{
ApplyOperator(Operator.Divide);
}
private void btnMultiply_Click(object sender, EventArgs e)
{
ApplyOperator(Operator.Multiply);
}
private void btnEquals_Click(object sender, EventArgs e)
{
Evaluate();
txtDisplay.Text = Convert.ToString(total);
}
private void Evaluate()
{
switch (currentOperator)
{
case Operator.Add:
total += currentValue;
break;
case Operator.Minus:
total -= currentValue;
break;
case Operator.Divide:
total /= currentValue;
break;
case Operator.Multiply:
total *= currentValue;
break;
case Operator.None:
break;
}
currentValue = 0;
currentOperator = Operator.None;
}
private void ApplyOperator(Operator op)
{
if (currentOperator != Operator.None)
{
Evaluate();
}
else
{
total = double.Parse(txtDisplay.Text);
}
txtDisplay.Clear();
currentOperator = op;
}
private void ShowInput(String n)
{
txtDisplay.Text = txtDisplay.Text + n;
currentValue = double.Parse(txtDisplay.Text);
}
}
}
I would still recommend that you would end up making some form of operator parser. Take a look here or look in to the 'Shunting Yard' algorithm yourself.

Think about it. What the minus_clicked code is doing is adding all of the operands EXCEPT the last one together, and then the equals_clicked code is doing the arithmetic on the result of minus_clicked, and the value of the textbox (which is the last operand, I assume). So, since the operation you're doing in minus_clicked is addition, what you're getting for x - y - z is really:
(X + Y) - Z
I would consider refactoring a little bit, but if you wanted to keep the code the way it is, I'd probably just change the minus_clicked code to subtract rather than add.
Also, #rhysw is right. If you wan't this to be fully functional, you're gonna have to add priority logic to it as well.

in your code:
private void btnMultiply_Click(object sender, EventArgs e)
{
total1 = total1 + double.Parse(txtDisplay.Text);
txtDisplay.Clear();
plusButtonClicked = false;
minusButtonClicked = false;
divideButtonClicked = false;
multiplyButtonClicked = true;
}
you aren't applying the correct operator, you have total1 = total1 + ... Change the operator to *.

The logic for calculating the product, quotient, and difference in your code is total1 = total1 + double.Parse(txtDisplay.Text); which is why the addition works, but nothing else. So change the logic so it either divides, multiplies, or subtracts, instead of adding.

I looked at the code, and it looks like in each button you're just adding each time. So any time to click a button you're just going to keep adding. Just change the opps to their appropriate button. like so:
private void btnMinus_Click(object sender, EventArgs e)
{
plusButtonClicked = false;
minusButtonClicked = true;
divideButtonClicked = false;
multiplyButtonClicked = false;
total1 = total1 - double.Parse(txtDisplay.Text);
txtDisplay.Clear();
}
private void btnDivide_Click(object sender, EventArgs e)
{
total1 = total1 / double.Parse(txtDisplay.Text);
txtDisplay.Clear();
plusButtonClicked = false;
minusButtonClicked = false;
divideButtonClicked = true;
multiplyButtonClicked = false;
}

Related

c#: Using enter for KeyDown does not work

I am playing with a basic calculator windows app and trying to make it calculate the equation when pressing the enter key. Currently, if I give it 2+2 and click my equal button it registers 4, as it should. I would like to get the same response when I hit the enter key on the keyboard. I am attempting to do this with this code:
if (e.KeyCode == Keys.Enter)
{
equal.PerformClick();
}
the result is 2+22(last number entered is duplicated)
However, if I use a letter or F-key(as in the below code) it returns the correct answer:
if (e.KeyCode == Keys.C)
{
equal.PerformClick();
}
For reference the following is the code that "equal.PerformClick()" is calling
decimal numA;
decimal numB;
decimal result = 0;
//-------------------------------------------------------------
decimal.TryParse(this.first_num_label.Text, out numA);
decimal.TryParse(this.label1.Text, out numB);
if (this.operator_name.Text == "+")
{
result = numA + numB;
}
//---------------------------------------------------------------
if (this.operator_name.Text == "-")
{
result = numA - numB;
}
//---------------------------------------------------------------
if (this.operator_name.Text == "x")
{
result = numA * numB;
}
//---------------------------------------------------------------
if (this.operator_name.Text == "/")
{
result = numA / numB;
}
//---------------------------------------------------------------
this.label1.Text = result.ToString();
this.first_num_label.Text = "";
this.operator_name.Text = "";
here is the entire code:.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Calc_project
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void clear_Click(object sender, EventArgs e)
{
//this.label1.Text = "";
this.label1.ResetText();
}
private void one_Click(object sender, EventArgs e)
{
this.label1.Text = this.label1.Text + "1";
}
private void two_Click(object sender, EventArgs e)
{
this.label1.Text = this.label1.Text + "2";
}
private void three_Click(object sender, EventArgs e)
{
this.label1.Text = this.label1.Text + "3";
}
private void four_Click(object sender, EventArgs e)
{
this.label1.Text = this.label1.Text + "4";
}
private void five_Click(object sender, EventArgs e)
{
this.label1.Text = this.label1.Text + "5";
}
private void six_Click(object sender, EventArgs e)
{
this.label1.Text = this.label1.Text + "6";
}
private void seven_Click(object sender, EventArgs e)
{
this.label1.Text = this.label1.Text + "7";
}
private void eight_Click(object sender, EventArgs e)
{
this.label1.Text = this.label1.Text + "8";
}
private void nine_Click(object sender, EventArgs e)
{
this.label1.Text = this.label1.Text + "9";
}
private void zero_Click(object sender, EventArgs e)
{
this.label1.Text = this.label1.Text + "0";
}
private void plus_Click(object sender, EventArgs e)
{
this.operator_name.Text = "+";
if (this.label1.Text != "")
{
this.first_num_label.Text = this.label1.Text;
}
this.label1.ResetText();
}
private void minus_Click(object sender, EventArgs e)
{
this.operator_name.Text = "-";
if (this.label1.Text != "")
{
this.first_num_label.Text = this.label1.Text;
}
this.label1.ResetText();
}
private void multiply_Click(object sender, EventArgs e)
{
this.operator_name.Text = "x";
if (this.label1.Text != "")
{
this.first_num_label.Text = this.label1.Text;
}
this.label1.ResetText();
}
private void div_Click(object sender, EventArgs e)
{
this.operator_name.Text = "/";
if (this.label1.Text != "")
{
this.first_num_label.Text = this.label1.Text;
}
this.label1.ResetText();
}
private void equal_Click(object sender, EventArgs e)
{
decimal numA;
decimal numB;
decimal result = 0;
//-------------------------------------------------------------
decimal.TryParse(this.first_num_label.Text, out numA);
decimal.TryParse(this.label1.Text, out numB);
if (this.operator_name.Text == "+")
{
result = numA + numB;
}
//---------------------------------------------------------------
if (this.operator_name.Text == "-")
{
result = numA - numB;
}
//---------------------------------------------------------------
if (this.operator_name.Text == "x")
{
result = numA * numB;
}
//---------------------------------------------------------------
if (this.operator_name.Text == "/")
{
result = numA / numB;
}
//---------------------------------------------------------------
this.label1.Text = result.ToString();
this.first_num_label.Text = "";
this.operator_name.Text = "";
}
private void button1_Click(object sender, EventArgs e)
{
this.label1.ResetText();
this.first_num_label.ResetText();
this.operator_name.ResetText();
}
private void Decimal_Click(object sender, EventArgs e)
{
this.label1.Text = this.label1.Text + ".";
}
private void button2_Click(object sender, EventArgs e)
{
decimal len;
decimal wit;
decimal area;
decimal.TryParse(this.textBox1.Text, out len);
decimal.TryParse(this.textBox2.Text, out wit);
area = len * wit;
if (ft.Checked == true)
{
this.label2.Text = area.ToString() +" square feet";
}
if (meters.Checked == true)
{
this.label2.Text = area.ToString() +" square meters";
}
if (cm.Checked == true)
{
this.label2.Text = area.ToString() + " square centimeters";
}
if (yards.Checked == true)
{
this.label2.Text = area.ToString() + " square yards";
}
//else
//{
// this.label2.Text = area.ToString();
//}
}
private void button3_Click(object sender, EventArgs e)
{
this.textBox1.Text = "";
this.textBox2.Text = "";
this.label2.ResetText();
}
private void button4_Click(object sender, EventArgs e)
{
decimal ar;
decimal cov;
decimal req;
//--------------------------------------------
decimal.TryParse(this.textBox4.Text, out ar);
decimal.TryParse(this.textBox3.Text, out cov);
//--------------------------------------------
req = ar / cov;
this.requirement.Text = req.ToString() + " Gallons";
}
private void button5_Click(object sender, EventArgs e)
{
decimal Slabar;
decimal Slabtk;
decimal TKft;
decimal cubFt;
decimal ConYard;
//--------------------------------------------
decimal.TryParse(this.textBox5.Text, out Slabar);
decimal.TryParse(this.textBox6.Text, out Slabtk);
//--------------------------------------------
TKft = Slabtk / 12;
cubFt = Slabar * TKft;
ConYard = cubFt / 27;
//--------------------------------------------
this.label10.Text = ConYard.ToString();
}
private void tabControl1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
equal.PerformClick();
}
if (e.KeyCode == Keys.F1) //this code works
{
MessageBox.Show("test");
}
if (e.KeyCode == Keys.Escape) //so does this
{
this.Close();
}
if (e.KeyCode == Keys.NumPad9) // also works
{
this.label1.Text = this.label1.Text + "9";
}
if (e.KeyCode == Keys.F2)
{
equal.PerformClick();
}
}
}
}
Based on my test, your code works well. If you still have problems, I suggest you can use Form_KeyDown event.
Here is a code example you can refer to.
public Form1()
{
InitializeComponent();
this.KeyPreview = true;
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
equal.PerformClick();
}
}
I fixed the control focus to textbox1 to prevent the Enter key from being affected by the input number.
After each number is entered, please set textBox1.Focus(). method.
As shown below:
private void one_Click(object sender, EventArgs e)
{
this.label1.Text = this.label1.Text + "1";
textBox1.Focus();
}
private void two_Click(object sender, EventArgs e)
{
this.label1.Text = this.label1.Text + "2";
textBox1.Focus();
}
......
......
Finally, it is best for you to check if the enter key is normal.
I'm assuming you are listening on the KeyPress event? If so, have you tried casting the Keys.Enter value to a char?
private void element_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
// Do stuff here
}
}
Keys.Enter and Keys.Return return the same value, so it doesn't matter which one you choose.

How to keep a value in text box after adding a decimal point

Hi I am struggling to keep a value in my calculator's text box when I add a decimal point to a number and then want to add another number after the decimal point. Here is my code:
What code must I add to keep the value in the text box after I added a decimal point? Thank you!
public Form1()
{
InitializeComponent();
}
double total1 = 0;
double total2 = 0;
bool plusButtonClicked = false;
bool subtractButtonClicked = false;
bool multiplyButtonClicked = false;
bool divideButtonClicked = false;
private void btnSeven_Click(object sender, EventArgs e)
{
txtDisplay.Text = btnSeven.Text;
}
private void btnNine_Click(object sender, EventArgs e)
{
txtDisplay.Text = btnNine.Text;
}
private void btnEquals_Click(object sender, EventArgs e)
{
if (plusButtonClicked == true)
{
total2 = total1 + double.Parse(txtDisplay.Text);
}
else if (subtractButtonClicked == true)
{
total2 = total1 - double.Parse(txtDisplay.Text);
}
else if (multiplyButtonClicked == true)
{
total2 = total1 * double.Parse(txtDisplay.Text);
}
else if (divideButtonClicked == true)
{
total2 = total1 / double.Parse(txtDisplay.Text);
}
{
txtDisplay.Text = total2.ToString();
total1 = 0;
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
total1 = total1 + double.Parse(txtDisplay.Text);
txtDisplay.Clear();
plusButtonClicked = true;
subtractButtonClicked = false;
multiplyButtonClicked = false;
divideButtonClicked = false;
}
private void btnOne_Click(object sender, EventArgs e)
{
txtDisplay.Text = btnOne.Text;
}
private void btnTwo_Click(object sender, EventArgs e)
{
txtDisplay.Text = btnTwo.Text;
}
private void btnThree_Click(object sender, EventArgs e)
{
txtDisplay.Text = btnThree.Text;
}
private void btnFour_Click(object sender, EventArgs e)
{
txtDisplay.Text = btnFour.Text;
}
private void btnFive_Click(object sender, EventArgs e)
{
txtDisplay.Text = btnFive.Text;
}
private void btnSix_Click(object sender, EventArgs e)
{
txtDisplay.Text = btnSix.Text;
}
private void btnEight_Click(object sender, EventArgs e)
{
txtDisplay.Text = btnEight.Text;
}
private void btnPoint_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnPoint.Text;
}
private void btnZero_Click(object sender, EventArgs e)
{
txtDisplay.Text = btnZero.Text;
}
private void btnSubtract_Click(object sender, EventArgs e)
{
total1 = total1 + double.Parse(txtDisplay.Text);
txtDisplay.Clear();
plusButtonClicked = false;
subtractButtonClicked = true;
multiplyButtonClicked = false;
divideButtonClicked = false;
}
private void btnMultiply_Click(object sender, EventArgs e)
{
total1 = total1 + double.Parse(txtDisplay.Text);
txtDisplay.Clear();
plusButtonClicked = false;
subtractButtonClicked = false;
multiplyButtonClicked = true;
divideButtonClicked = false;
}
private void btnDivide_Click(object sender, EventArgs e)
{
total1 = total1 + double.Parse(txtDisplay.Text);
txtDisplay.Clear();
plusButtonClicked = false;
subtractButtonClicked = false;
multiplyButtonClicked = false;
divideButtonClicked = true;
}
private void btnClear_Click(object sender, EventArgs e)
{
txtDisplay.Clear();
}
}
}
The issue seems to be that you are doing this:
private void some_button_Click(object sender, EventArgs e)
{
txtDisplay.Text = btnEight.Text;
}
So, if you click 4, and then . it'll show 4. , but when you click 5, it'll set it to 5.
You need to add to the previous on all your numbers ... (just like you do with the . button)
As Noctis said you need to add to the previous in all your click events. Like :
private void some_button_Click(object sender, EventArgs e)
{
txtDisplay.Text += ((Button)sender).Text;
}
the answer is simple
txtDisplay.Text += Button.Text;
Improve your code
public class Form1:Form
{
public enum CalcStatus
{
None,
Plus,
Minus,
Divide,
Multiply
};
CalcStatus status = CalcStatus.None;
bool bHasNewFlag = false;
bool bHasEquals = false;
Decimal dMemory1 = 0M;
Decimal dMemory2 = 0M;
private void CalcButton_Click(object sender, EventArgs e) // This event will be handled by Plus,Minus,Devide and Multiply
{
Decimal.TryParse(txtDisplay.Text,out dMemory1);
switch(((button)sender).Text)
{
case "+":
status = CalcStatus.Plus;
break;
case "-":
status = CalcStatus.Minus;
break;
case "/":
status = CalcStatus.Divide;
break;
case "*":
status = CalcStatus.Multiply;
break;
}
bHasNewFlag = true;
bHasEquals =false;
dMemroy2 = 0M;
}
private void NumButton_Click(object sender, EventArgs e) // This event will be handled by numbers (0-9)
{
int iNumber = 0;
int.TryParse(((button)sender).Text, out iNumber);
if (bHasNewFlag)
txtDisplay.Text = string.empty;
txtDisplay.Text += iNumber.ToString();
bHasEquals =false;
dMemroy2 = 0M;
}
private void EqualsTo_Click(object sender, EventArgs e) // This event will be handled by Equals To (=)
{
Decimal dVal = 0M;
if (bHasEquals == false)
Decimal.TryParse(txtDisplay.Text, out dMemory1);
switch(status)
{
case "+":
dVal = dMemory1 + dMemory2;
break;
case "-":
status = CalcStatus.Minus;
dVal = dMemory1 - dMemory2;
break;
case "/":
dVal = dMemory1 / dMemory2;
break;
case "*":
dVal = dMemory1 * dMemory2;
break;
}
txtDisplay.Text = dVal;
bHasEquals =true;
}
}
Do not take boolean flag for each button. because, you can do one thing at one time.
Updates:
My suggestion is when you have status like Plus, Minus, Divide, etc. then you can do any one thing at a time.
for example here you have to manage 4 variables on each button click instead of one.
so use Enumaration when you have single status value.
public enum CalcStatus
{
None,
Plus,
Minus,
Divide,
Multiply
};
CalcStatus status = CalcStatus.None;

Getting my calculator to take a new number after the equal button is pressed

So I have been at this for a while now and still cannot get my calculator to do one final thing.
I got it thanks!
After I push the equal button or Tan, Sin, Cos or Mod buttons I want my calculator to take a new number. Basically as if nothing was in the textbox even though the answer is still there. Currently, all the numbers stay and the new number is added to the end. I do not want this to happen.
After the calculation, if I push a number button I want it to clear the screen and add the new number fresh. Below is my code that I have so far.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Double FirstNumber;
string mathOperator = "";
private void AddButton_Click(object sender, EventArgs e)
{
FirstNumber = Convert.ToDouble(DisplayTextBox.Text);
mathOperator = "+";
DisplayTextBox.Text = "";
DisplayTextBox.Focus();
}
private void EqualButton_Click(object sender, EventArgs e)
{
Double SecondNumber;
SecondNumber = Convert.ToDouble(DisplayTextBox.Text);
switch (mathOperator)
{
case "+":
DisplayTextBox.Text = (FirstNumber + SecondNumber).ToString();
break;
case "-":
DisplayTextBox.Text = (FirstNumber - SecondNumber).ToString();
break;
case "*":
DisplayTextBox.Text = (FirstNumber * SecondNumber).ToString();
break;
case "/":
DisplayTextBox.Text = (FirstNumber / SecondNumber).ToString();
break;
default:
break;
}
}
private void button12_Click(object sender, EventArgs e)
{
FirstNumber = Convert.ToDouble(DisplayTextBox.Text);
FirstNumber *= -1;
DisplayTextBox.Text = FirstNumber.ToString();
}
private void ButtonMinus_Click(object sender, EventArgs e)
{
FirstNumber = Convert.ToDouble(DisplayTextBox.Text);
mathOperator = "-";
DisplayTextBox.Text = "";
DisplayTextBox.Focus();
}
private void ButtonMultiply_Click(object sender, EventArgs e)
{
FirstNumber = Convert.ToDouble(DisplayTextBox.Text);
mathOperator = "*";
DisplayTextBox.Text = "";
DisplayTextBox.Focus();
}
private void ButtonDivide_Click(object sender, EventArgs e)
{
FirstNumber = Convert.ToDouble(DisplayTextBox.Text);
mathOperator = "/";
DisplayTextBox.Text = "";
DisplayTextBox.Focus();
}
private void ButtonMod_Click(object sender, EventArgs e)
{
FirstNumber = Convert.ToDouble(DisplayTextBox.Text);
DisplayTextBox.Text = Math.Tan(FirstNumber).ToString();
}
private void Button1_Click(object sender, EventArgs e)
{
DisplayTextBox.Text = DisplayTextBox.Text + "1";
}
private void Button2_Click(object sender, EventArgs e)
{
DisplayTextBox.Text = DisplayTextBox.Text + "2";
}
private void Button3_Click(object sender, EventArgs e)
{
DisplayTextBox.Text = DisplayTextBox.Text + "3";
}
private void Button4_Click(object sender, EventArgs e)
{
DisplayTextBox.Text = DisplayTextBox.Text + "4";
}
private void Button5_Click(object sender, EventArgs e)
{
DisplayTextBox.Text = DisplayTextBox.Text + "5";
}
private void Button6_Click(object sender, EventArgs e)
{
DisplayTextBox.Text = DisplayTextBox.Text + "6";
}
private void Button7_Click(object sender, EventArgs e)
{
DisplayTextBox.Text = DisplayTextBox.Text + "7";
}
private void Button8_Click(object sender, EventArgs e)
{
DisplayTextBox.Text = DisplayTextBox.Text + "8";
}
private void Button9_Click(object sender, EventArgs e)
{
DisplayTextBox.Text = DisplayTextBox.Text + "9";
}
private void ButtonClear_Click(object sender, EventArgs e)
{
DisplayTextBox.Text = "";
mathOperator = "";
}
private void ButtonOff_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void ButtonTan_Click(object sender, EventArgs e)
{
FirstNumber = Convert.ToDouble(DisplayTextBox.Text);
DisplayTextBox.Text = Math.Tan(FirstNumber).ToString();
}
private void ButtonSin_Click(object sender, EventArgs e)
{
FirstNumber = Convert.ToDouble(DisplayTextBox.Text);
DisplayTextBox.Text = Math.Sin(FirstNumber).ToString();
}
private void ButtonCos_Click(object sender, EventArgs e)
{
FirstNumber = Convert.ToDouble(DisplayTextBox.Text);
DisplayTextBox.Text = Math.Cos(FirstNumber).ToString();
}
private void Button0_Click(object sender, EventArgs e)
{
if (DisplayTextBox.Text.Length >= 1)
{
DisplayTextBox.Text = DisplayTextBox.Text + "0";
}
else
{
return;
}
}
private void DecimalButton_Click(object sender, EventArgs e)
{
if (DisplayTextBox.Text.Contains("."))
{
return;
}
else
{
DisplayTextBox.Text = DisplayTextBox.Text + ".";
}
}
}
Add a Boolean variable to your class that represents a flag of whether or not an operation has just completed or not, like this:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Double FirstNumber;
string mathOperator = "";
bool operationJustCompleted = false;
Initially, the value will be false, because nothing has happened when the calculator is first created.
Now, at the end of the equal button event handler, set the flag to true, like this:
private void EqualButton_Click(object sender, EventArgs e)
{
// Logic for calculation
operationJustCompleted = true;
}
Finally, in the event handlers for the number buttons, check to see if the operationJustCompleted flag is true, if so then clear the text and reset the operation just completed flag back to false; like this:
private void Button1_Click(object sender, EventArgs e)
{
if(operationJustCompleted)
{
DisplayTextBox.Text = String.Empty;
operationJustCompleted = false;
}
DisplayTextBox.Text = DisplayTextBox.Text + "1";
}
Add a state variable to your class. When true, and a number is selected, clear the display and set it false before writing the number.
When "=" is clicked, set it true.
Based on a brief review, seems like you need to introduce a variable that will keep track of the calculator’s state, and then when “equal” button is pressed, set the state to calculated value. Then, in the numeric buttons (0-9) you need to check the state variable and either append to or replace the display text.
Create this global variable...
private bool equationComplete = false;
Add this to the end of the Equals button...
equationComplete = true;
Add this to the beginning of each number button click...
if (equationComplete) DisplayTextBox.Text = "";
Add this to the end of each number button click event handler...
equationComplete = false;
Just like David Arno says, something like this:
private void EqualButton_Click(object sender, EventArgs e)
{
ClearDisplayBeforeNextTextEntry = true;
}
private void Button1_Click(object sender, EventArgs e)
{
// New code
ClearText();
// Old code
DisplayTextBox.Text = DisplayTextBox.Text + "1";
}
// Same for all other number buttons as above
private void ClearText()
{
if (ClearDisplayBeforeNextTextEntry)
{
DisplayTextBox.Text = "";
ClearDisplayBeforeNextTextEntry = false;
}
}

How do I overwrite in a calculator?

This is my code for the calculator written in SharpDevelop. I need to know how to overwrite a number.
In my code when I'm texting the first number and after i press the add button the textbox gets cleared.
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
double total1 = 0;
double total2 = 0;
void BtnOneClick(Object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnOne.Text;
}
void BtnTwoClick(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnTwo.Text;
}
...
void BtnZeroClick(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnZero.Text;
}
void BtnClearClick(object sender, EventArgs e)
{
txtDisplay.Clear();
}
void BtnPlusClick(object sender, EventArgs e)
{
total1 += double.Parse(txtDisplay.Text);
txtDisplay.Clear();
plusButtonClicked = true;
minusButtonClicked = false;
multiplyButtonClicked = false;
divideButtonClicked = false;
}
...
bool plusButtonClicked = false;
bool minusButtonClicked = false;
bool multiplyButtonClicked = false;
bool divideButtonClicked = false;
}
i think you want
void BtnPlusClick(object sender, EventArgs e)
{
total1 += double.Parse(txtDisplay.Text);
txtDisplay.Text = total1.toString();
Edit: .Clear will remove the text from the text box.. I think if you wanted something else to happen then you need to rethink what you are trying to do
Edit2 if this isnt what you wanted I dont know what is
int total = 0;
bool newNum = true;
//1
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = newNum ? "1" : textBox1.Text + "1";
newNum = false;
}
//Add
private void button2_Click(object sender, EventArgs e)
{
newNum = true;
total += int.Parse(textBox1.Text);
textBox1.Clear();
}
//Equals
private void button3_Click(object sender, EventArgs e)
{
textBox1.Text = total.ToString();
}
It's beacause of this line:
txtDisplay.Clear();
in your method
BtnPlusClick();
if you want to clear it only when you start to provide next number - just chceck your bool flags(plusButtonClicked, etc.) - if on of them is set to true - then make
txtDisplay.Clear();

How would I use and implement a MaskedTextBox into my Calculator application? C#

So I'm working on a calculator application in C-Sharp and I want to prevent people from entering more than 1 period/point at once. So they can't type "....." or "1..1" or "1.1.1"
Really just stuff like that.... I would also like to prevent them from adding alphabetical characters in by typing them in with the keyboard, characters like "a, b, c".
I was told to use a MaskedTextBox, and I want to know if that is correct. Also, if it is correct, how would I implement it into my code? I'm a complete beginner when it comes to C#, so I would like some help (toned down for a beginner).
So far the code I have written is:
double total1 = 0;
double total2 = 0;
public Form1()
{
InitializeComponent();
}
private void btnOne_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnOne.Text;
}
private void btnTwo_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnTwo.Text;
}
private void btnThree_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnThree.Text;
}
private void btnFour_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnFour.Text;
}
private void btnFive_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnFive.Text;
}
private void btnSix_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnSix.Text;
}
private void btnSeven_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnSeven.Text;
}
private void btnEight_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnEight.Text;
}
private void btnNine_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnNine.Text;
}
private void btnZero_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnZero.Text;
}
private void btnClear_Click(object sender, EventArgs e)
{
txtDisplay.Clear();
}
private void btnPlus_Click(object sender, EventArgs e)
{
total1 = total1 + double.Parse(txtDisplay.Text);
txtDisplay.Clear();
}
private void btnEquals_Click(object sender, EventArgs e)
{
total2 = total1 + double.Parse(txtDisplay.Text);
txtDisplay.Text = total2.ToString();
total1 = 0;
}
private void btnPoint_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnPoint.Text;
}
private void label1_Click(object sender, EventArgs e)
{
}
private void txtDisplay_TextChanged(object sender, EventArgs e)
{
}
}
So I ask... how/where do I add in this "MaskedTextBox" - if that is correct? How do I implement it? What makes it work?
Thanks!
You don't need a MaskedTextBox, since you're simulating the keypad with your buttons. Just put something like this in btnPoint_Click:
private void btnPoint_Click(object sender, EventArgs e)
{
if (!txtDisplay.Text.Contains("."))
{
txtDisplay.Text = txtDisplay.Text + btnPoint.Text;
}
}
In addition to MusiGenesis's snippet, you can use the KeyPress event of the text box to prevent non-digits and multiple periods.
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if(char.IsDigit(e.KeyChar) || ((e.KeyChar == '.' && textBox1.Text.IndexOf(".") < 0) ) )
{
textBox1.Text += e.KeyChar;
}
e.Handled = true;
}
or set ReadOnly property of the text box to true.
You can also save a big amount of code if you write the code of the click event just once and asign the click event handlers of every number buttons to it:
private void btnNumber_Click(object sender, EventArgs e)
{
if (sender is Button)
txtDisplay.Text = txtDisplay.Text + ((Button)sender).Text;
}
So you can save all of the following methods
private void btnZero_Click(object sender, EventArgs e) (...)
private void btnOne_Click(object sender, EventArgs e) (...)
.
.
.
private void btnNine_Click(object sender, EventArgs e) (...)

Categories

Resources