C# Calculator - textBox to listBox - c#

This calculator is extremely basic and so I'm only working with two values to calculate at a time.
I am calculating two values only val1 and val2. These values can be of any size including a decimal point.
I have buttons for numbers 0-9, a decimal point, plus, minus, divide, multiply and equals.
I want val1, val2 and the operator(ex. +,-,/,*) I choose to calculate these values to appear in my listBox after I hit the = button. Every calculation I make I want it added to the listBox underneath the previous calculation. When the listBox grows to a certain amount of calculations (10-15ish) I want the oldest calculation removed from the bottom and the newest added to the top of the list.
public partial class Form1 : Form
{
// global variables
bool plus = false;
bool minus = false;
bool multiply = false;
bool divide = false;
bool equal = false;
public Form1()
{
InitializeComponent();
} // **MUST HAVE**
private void button0_Click(object sender, EventArgs e)
{
CheckIfEqual();
textBox1.Text = textBox1.Text + "0";
} // makes number click usable
private void CheckIfEqual()
{
if (equal) // checks if equal is true
{
textBox1.Text = ""; // clear textBox
equal = false; // tells program there is new calculation
}
}
private void button1_Click(object sender, EventArgs e)
{
CheckIfEqual();
textBox1.Text = textBox1.Text + "1";
} // makes number click usable
private void button2_Click(object sender, EventArgs e)
{
CheckIfEqual();
textBox1.Text = textBox1.Text + "2";
} // makes number click usable
private void button3_Click(object sender, EventArgs e)
{
CheckIfEqual();
textBox1.Text = textBox1.Text + "3";
} // makes number click usable
private void button4_Click(object sender, EventArgs e)
{
CheckIfEqual();
textBox1.Text = textBox1.Text + "4";
} // makes number click usable
private void button5_Click(object sender, EventArgs e)
{
CheckIfEqual();
textBox1.Text = textBox1.Text + "5";
} // makes number click usable
private void button6_Click(object sender, EventArgs e)
{
CheckIfEqual();
textBox1.Text = textBox1.Text + "6";
} // makes number click usable
private void button7_Click(object sender, EventArgs e)
{
CheckIfEqual();
textBox1.Text = textBox1.Text + "7";
} // makes number click usable
private void button8_Click(object sender, EventArgs e)
{
CheckIfEqual();
textBox1.Text = textBox1.Text + "8";
} // makes number click usable
private void button9_Click(object sender, EventArgs e)
{
CheckIfEqual();
textBox1.Text = textBox1.Text + "9";
} // makes number click usable
private void buttonDecimal_Click(object sender, EventArgs e)
{
CheckIfEqual();
if (textBox1.Text.Contains("."))
{
return;
} // if it contains a decimal execute
else
{
textBox1.Text = textBox1.Text + ".";
} // adds decimal
} // end decimal
private void buttonPlusMinus_Click(object sender, EventArgs e)
{
if (textBox1.Text.Contains("-"))
{
textBox1.Text = textBox1.Text.Remove(0, 1);
} // if it contains the - character remove it
else
{
textBox1.Text = "-" + textBox1.Text;
} //
} // adds/removes -
private void buttonPlus_Click(object sender, EventArgs e)
{
if (textBox1.Text == "")
{
return;
} // if textbox is empty return
else
{
plus = true;
textBox1.Tag = textBox1.Text; // stores number
textBox1.Text = ""; // clears textbox
} // tells program we are adding
} // end plus
private void buttonMinus_Click(object sender, EventArgs e)
{
if (textBox1.Text == "")
{
return;
} // if textbox is empty return
else
{
minus = true;
textBox1.Tag = textBox1.Text; // stores number
textBox1.Text = ""; // clears textbox
} // tells program we are subtracting
}
private void buttonMultiply_Click(object sender, EventArgs e)
{
if (textBox1.Text == "")
{
return;
} // if textbox is empty return
else
{
multiply = true;
textBox1.Tag = textBox1.Text; // stores number
textBox1.Text = ""; // clears textbox
} // tells program we are multiplying
}
private void buttonDivide_Click(object sender, EventArgs e)
{
if (textBox1.Text == "")
{
return;
} // if textbox is empty return
else
{
divide = true;
textBox1.Tag = textBox1.Text; // stores number
textBox1.Text = ""; // clears textbox
} // tells program we are dividing
}
private void buttonEquals_Click(object sender, EventArgs e)
{
equal = true; // tells program it made a calculation
if (plus) // if true execute
{
decimal dec = Convert.ToDecimal(textBox1.Tag) + Convert.ToDecimal(textBox1.Text);
textBox1.Text = dec.ToString(); // display value once add is finished
plus = false;
} // end if plus
if (minus) // if true execute
{
decimal dec = Convert.ToDecimal(textBox1.Tag) - Convert.ToDecimal(textBox1.Text);
textBox1.Text = dec.ToString(); // display value once add is finished
minus = false;
} // end if minus
if (multiply) // if true execute
{
decimal dec = Convert.ToDecimal(textBox1.Tag) * Convert.ToDecimal(textBox1.Text);
textBox1.Text = dec.ToString(); // display value once add is finished
multiply = false;
} // end if multiply
try
{
if (divide) // if true execute
{
decimal dec = Convert.ToDecimal(textBox1.Tag) / Convert.ToDecimal(textBox1.Text);
textBox1.Text = dec.ToString(); // display value once add is finished
divide = false;
} // end if divide
} // try
catch (DivideByZeroException ex)
{
MessageBox.Show(ex.Message, "ERROR", MessageBoxButtons.OK);
} // catch
} // end buttonEquals
private void buttonClear_Click(object sender, EventArgs e)
{
plus = minus = multiply = divide = false; // makes all false regardless
textBox1.Text = ""; // clear
textBox1.Tag = ""; // clears
}
} // end partial class Form1
}// end namespace

Refactoring would be nice...
For example, you can use the same method for all your "numeric button click" event.
instead of
private void button1_Click(object sender, EventArgs e)
{
CheckIfEqual();
textBox1.Text = textBox1.Text + "1";
} // makes number click usable
...
private void button9_Click(object sender, EventArgs e)
{
CheckIfEqual();
textBox1.Text = textBox1.Text + "9";
} // makes number click usable
just use one method.
button1.Click += NumericButtonClick;
...
button9.Click +=NumericButtonClick;
private void NumericButtonClick(object sender, EventArgs e) {
CheckIfEqual();
textBox1.Text = textBox1.Text + ((Button)sender).Text;
}
Anyway.
Say you have a ListBox historyListBox;
Then just add a method
private void PopulateListBox(string left, string right, string operator) {
var newContent = string.Format("{0} {1} {2}", left, operator, right);
if (historyListBox.Items.Count == 15)
historyListBox.Items.RemoveAt(14);//
historyListBox.Items.Insert(0, newContent);
}
and then you could change the "equal_click event" (which sould be also refactored, but that's another problem)
private void buttonEquals_Click(object sender, EventArgs e)
{
var left = textBox1.Tag;
var right = textBox1.Text;
var operator = string.Empty;
equal = true; // tells program it made a calculation
if (plus) // if true execute
{
operator = "+";
decimal dec = Convert.ToDecimal(left) + Convert.ToDecimal(right);
textBox1.Text = dec.ToString(); // display value once add is finished
plus = false;
} // end if plus
if (minus) // if true execute
{
operator = "-";
decimal dec = Convert.ToDecimal(left) - Convert.ToDecimal(right);
textBox1.Text = dec.ToString(); // display value once add is finished
minus = false;
} // end if minus
//...etc
PopulateListBox(left, right, operator);
}

Related

Vehicle Loan Calculator - Having trouble with my program outputting the correct values

I have been trying to get my amortization calculator to work however the ending payment balance does not end on 0 and my code does not output the correct values and I am stuck after doing some googling for a couple hours. I believe my issue is underneath the comment "Listbox Loop." Any help would be appreciated.
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void MainForm_Load(object sender, EventArgs e)
{
// Allows for the hotkeys to be used even when out of focus from main form
this.KeyPreview = true;
}
private void MainForm_KeyPress(object sender, KeyPressEventArgs e)
{
// Adds hotkeys; Enter = Calculate, Escape = Exit
if (e.KeyChar == (char)Keys.Enter)
{
calculateButton.PerformClick();
}
else if (e.KeyChar == (char)Keys.Escape)
{
exitButton.PerformClick();
}
}
private void rebateCheck_CheckedChanged(object sender, EventArgs e)
{
// Enables & Disables rebate textbox based on rebate checkbox
if (rebateCheck.Checked == true)
{
rebateBox.Enabled = true;
}
else
{
rebateBox.Clear();
rebateBox.Enabled = false;
}
}
/* Selects data inside of the textbox when tabbing or clicking into it */
private void loanAmountBox_Enter(object sender, EventArgs e)
{
loanAmountBox.SelectAll();
}
private void loanAmountBox_Click(object sender, EventArgs e)
{
loanAmountBox.SelectAll();
}
private void annualAPRBox_Enter(object sender, EventArgs e)
{
annualAPRBox.SelectAll();
}
private void annualAPRBox_Click(object sender, EventArgs e)
{
annualAPRBox.SelectAll();
}
private void rebateBox_Enter(object sender, EventArgs e)
{
rebateBox.SelectAll();
}
private void rebateBox_Click(object sender, EventArgs e)
{
rebateBox.SelectAll();
}
/* Clears the list box when text is changed on any of the input boxes */
private void loanAmountBox_TextChanged(object sender, EventArgs e)
{
loanListBox.Items.Clear();
}
private void annualAPRBox_TextChanged(object sender, EventArgs e)
{
loanListBox.Items.Clear();
}
private void rebateBox_TextChanged(object sender, EventArgs e)
{
loanListBox.Items.Clear();
}
/* Only allows digits, periods, and control keys to be entered into textboxes */
private void loanAmountBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !Char.IsDigit(e.KeyChar) && e.KeyChar != '.')
{
e.Handled = true;
return;
}
}
private void annualAPRBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !Char.IsDigit(e.KeyChar) && e.KeyChar != '.')
{
e.Handled = true;
return;
}
}
private void rebateBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !Char.IsDigit(e.KeyChar) && e.KeyChar != '.')
{
e.Handled = true;
return;
}
}
private void exitButton_Click(object sender, EventArgs e)
{
// Asks the user if they are sure they want to exit
DialogResult dialog = MessageBox.Show("Are you sure you want to exit?", this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Warning); ;
if (dialog == DialogResult.Yes)
this.Close();
}
private void calculateButton_Click(object sender, EventArgs e)
{
// Declaring all variables
int monthsCounter;
double loan;
double rate;
double rebate;
double principal;
double balance;
int months = 0;
double principalPayment = 0;
double pmt = 0;
double interest = 0;
double totalInterest = 0;
double totalPrincipal = 0;
double totalPayment = 0;
double monthlyRate;
try
{
// Parse data from textboxes
double.TryParse(loanAmountBox.Text, out loan);
double.TryParse(annualAPRBox.Text, out rate);
double.TryParse(rebateBox.Text, out rebate);
// Check which loan month radio button is selected
if (loan6Months.Checked)
{
months = 6;
}
else if (loan12Months.Checked)
{
months = 12;
}
else if (loan18Months.Checked)
{
months = 18;
}
else if (loans24Months.Checked)
months = 24;
// Validates if the Loan Amount textbox is blank and if so, throws an error message pop up
if (loan == 0)
{
MessageBox.Show("Please enter a loan value.", "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
loanAmountBox.Focus();
loanAmountBox.SelectAll();
}
else if (rate == 0)
{
MessageBox.Show("Please enter/select an APR value.", "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
annualAPRBox.Focus();
annualAPRBox.SelectAll();
}
rate = (rate / 100) / 12;
loan = loan - rebate;
// Listbox loop
for (monthsCounter = 1; monthsCounter <= months; monthsCounter = monthsCounter + 1)
{
// Add to total variables
totalInterest += interest;
totalPrincipal += principalPayment;
totalPayment += pmt;
// Calculate the principal payment
interest = loan * rate;
principalPayment = (loan * rate * Math.Pow(1 + rate, months)) / (Math.Pow(1 + rate, months) - 1);
pmt = principalPayment + interest;
loan = loan - principalPayment;
// Output data to listbox
loanListBox.Items.Add(String.Format("{0,5}{1,12}{2,12}{3,12}{4,12}", monthsCounter, interest.ToString("N2"), principalPayment.ToString("N2"), pmt.ToString("N2"), loan.ToString("N2")));
}
loanListBox.Items.Add("");
loanListBox.Items.Add(String.Format("{0,5}{1,12}{2,12}{3,12}", "Total", totalInterest.ToString("N2"), totalPrincipal.ToString("N2"), totalPayment.ToString("N2")));
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
}
This is what my output looks like when running the program:
However, the output is supposed to be this:
The formula you're using for amortization is correct, it's what you do after this that is giving you the wrong result. principalPayment is the total payment which includes interest. You should probably rename this to totalPayment because the name is misleading. If you know the total payment amount, and you know the interest. How are you going to get the principal amount?
Interest + Principal = Total Payment
Update:
Keep in mind that the loan value used in the amortization formula is not changed--the original loan amount is used for all calculations.
Any time you see "???", it means that you need to fill in the code.
You may consider adding a variable:
double originalLoanAmount = 0;
Then put the loan amount into originalLoanAmount.
double.TryParse(loanAmountBox.Text, out originalLoanAmount);
Set initial values before the "for" loop:
originalLoanAmount = ???
balance = ???
How do you calculate the interest?
interest = ???
Calculate total payment: (original loan amount doesn't change)
pmt = (originalLoanAmount * rate * Math.Pow(1 + rate, months)) / (Math.Pow(1 + rate, months) - 1);
What's the principalPayment?
principalPayment = ???
What's the new balance?
balance = ???

Stop and repeat process by using a timer in C# Windows Form

I am trying to use a timer to achieve a sort of old animation used in the past to show that a process is running.
The way I would like to do that is by adding dots to a sentence (in a label control), for example:
"Process is running." to "Process is running.." and "Process is running..." with a limit of 3 dots and then revert back to a single dot.
I am not sure as to the fact using a timer here would be the best choice, but I thought it should work fine for such a simple example.
The code I used is as follows:
public string InitialProcessText;
private void StartBtn_Click(object sender, EventArgs e)
{
if(fileName != "No file selected")
{
ValidationLbl.Text = null;
ProcessLbl.Text = "Application is now running.";
//InitialProcessText = ProcessLbl.Text;
ProcessTimer.Start();
}
else
{
ValidationLbl.Text = "No file was added";
}
}
private void StopBtn_Click(object sender, EventArgs e)
{
ProcessTimer.Stop();
}
private void ProcessTimer_Tick(object sender, EventArgs e)
{
_ticks++;
//For every two ticks, ProcessLbl.Text = InitialProcessText
ProcessLbl.Text += ".";
}
What could I add to set a limit of adding 2 dots and then remove the dots and add dots again (I would assume to do this in the ProcessTimer_Tick method)?
You can just use your _ticks variable:
private readonly int _ticksPerUpdate = 2;
private readonly int _maxNumberOfDots = 3;
private void ProcessTimer_Tick(object sender, EventArgs e)
{
_ticks++;
if(_ticks == (_ticksPerUpdate * (_maxNumberOfDots + 1)))
{
_ticks = 0;
ProcessLbl.Text = InitialProcessText;
}
else if(_ticks % _ticksPerUpdate == 0)
{
ProcessLbl.Text += ".";
}
}
Remember to reset the ticks counter every time you start the timer:
private void StartBtn_Click(object sender, EventArgs e)
{
if(fileName != "No file selected")
{
ValidationLbl.Text = null;
ProcessLbl.Text = "Application is now running.";
InitialProcessText = ProcessLbl.Text;
// reset the variable
_ticks = 0
ProcessTimer.Start();
}
else
{
ValidationLbl.Text = "No file was added";
}
}
I assume that _ticks counts the number of ticks. You could then go :
if(ticks%3 == 0)
{
ProcessLbl.Text = "Application is now running."
}
else
{
ProcessLbl.Text+=".";
}
Then, at 1st tick, 1%3=1 so it adds a dot, at 2nd tick, 2%3=2 so it adds a dot and 3rd tick, 3%3=0, so it gets back to original.
Just because...here's another approach:
private void ProcessTimer_Tick(object sender, EventArgs e)
{
ProcessLbl.Text = ProcessLbl.Text.EndsWith("...") ? ProcessLbl.Text.TrimEnd(".".ToCharArray()) + "." : ProcessLbl.Text + ".";
}

When I put two or more operators in eg '*' and error occurs, feel free to edit code

Operation error when two operations are clicked, i want error handling to take place so i cant put multiple * in a row
namespace Calculator_Assignment
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
float num, ans;
int count;
private void Form1_Load(object sender, EventArgs e)
{
}
private void Button_click(object sender, EventArgs e)
{
Button button = (Button)sender; //adds the numbers into the screen when clicked
Screen.Text = Screen.Text + button.Text;
Screen.ForeColor = Color.Red; //text that entered appears red
}
private void operatorclick(object sender, EventArgs e)
{
Button button = (Button)sender; //adds the symbols into the screen when clicked
Screen.Text = Screen.Text + button.Text; //all symbols are under button_click so i do not have to repeat the code over/
}
private void Clearclick(object sender, EventArgs e)
{
Screen.Clear(); //when clicked clears the screen
Result.Clear(); //when clicked clears the result
}
private void Decimalclick(object sender, EventArgs e)
{
Screen.Text = Screen.Text + "."; //adds decimal point to screen when/if clicked
Screen.ForeColor = Color.Red; //decimal point appears red
}
private void Closebtn_Click(object sender, EventArgs e)
{
this.Close(); // closes the application down
}
private void plusclick(object sender, EventArgs e) //addition
{
num = float.Parse(Screen.Text);
Screen.Clear(); //clears the screen of everything
Screen.Focus(); //textbox is focused upon when the screen is cleared
count = 1; //this counts the store case
Screen.Text = num.ToString() + "+"; //this puts the text onto the top text box
}
private void multiplyclick(object sender, EventArgs e) //multiply
{
num = float.Parse(Screen.Text);
Screen.Clear(); //clears the screen of everything
Screen.Focus(); //textbox is focused upon when the screen is cleared
count = 3; //this counts the store case
Result.Text = num.ToString() + "*"; //this puts the text onto the top textbox
}
private void divideclick(object sender, EventArgs e) //divide
{
num = float.Parse(Screen.Text);
Screen.Clear(); //clears the screen of everything
Screen.Focus(); //textbox is focused upon when the screen is cleared
count = 4; //this counts the store case
Screen.Text = num.ToString() + "/"; //this puts the text onto the
}
private void subtractclick(object sender, EventArgs e) //subtract
{
num = float.Parse(Screen.Text);
Screen.Clear(); //clears the screen of everything
Screen.Focus(); //textbox is focused upon when the screen is cleared
count = 2; //this counts the store case
Result.Text = num.ToString() + "-"; //this puts the text onto the label
}
private void equalsclick(object sender, EventArgs e)
{
switch (count) //initalising switch statement
{
case 1:
ans = num + float.Parse(Screen.Text);//Adding numbers
Result.Text = ans.ToString(); //this converts my answer from a float to a string
break;
case 2:
ans = num - float.Parse(Screen.Text); //Subtracting numbers
Result.Text = ans.ToString(); //float to a string
break;
case 3:
ans = num * float.Parse(Screen.Text); //Multiplying numbers
Result.Text = ans.ToString(); //float to a string
break;
case 4:
ans = num / float.Parse(Screen.Text); //Division of numbers
Result.Text = ans.ToString(); //float to a string
break;
default: //the default figure
break;
}
}
}
}
Quick solution:
Create a method called void AppendOperator(string operator)
This method should check the previous character before appending it. If the previous character is an operator then simply return.
Call this new method in place of all the locations where you assign a value to Result.Text
AppendOperator implementation example:
private readonly HashSet<char> _operators = new HashSet<char>() { '+', '*', '-', '/' };
void AppendOperator(string operation)
{
char lastChar = Result.Text.LastOrDefault();
if (_operators.Contains(lastChar)) return;
Result.Text = num.ToString() + operation;
}

Double result when using keypress

I made this calculator in C# and I have one problem: When I press keyboard something like 1 it gives me incorrect result double number. I don't get the correct result.
Do you know what I am doing wrong,
Thank you very much!
namespace Calculator
{
public partial class Calculator : Form
{
Double value = 0;
String operation = "";
int i = 0;
bool operation_pressed = false;
bool button_dot = false;
OperationClass class1 = new OperationClass();
public Calculator()
{
InitializeComponent();
this.KeyPreview = true;
this.KeyPress += new KeyPressEventHandler(Calculator_KeyPress);
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void Calculator_Load(object sender, EventArgs e)
{
}
private void Calculator_KeyPress(object sender, KeyPressEventArgs e)
{
if ((result.Text == "0") || (operation_pressed))
result.Clear();
switch (e.KeyChar)
{
// key press from 0-9
case (char)48:
case (char)49:
case (char)50:
case (char)51:
case (char)52:
case (char)53:
case (char)54:
case (char)55:
case (char)56:
case (char)57:
e.Handled = true;
result.Text += e.KeyChar.ToString();
break;
}
}
private void button_Click(object sender, EventArgs e)
{
if ((result.Text == "0") || (operation_pressed))
result.Clear();
operation_pressed = false;
Button b = (Button)sender;
result.Text = result.Text + b.Text;
}
private void operator_click(object sender, EventArgs e)
{
Button b = (Button)sender;
operation = b.Text;
value = Double.Parse(result.Text);
operation_pressed = true;
equation.Text = value + " " + operation;
}
private void buttonCE_Click(object sender, EventArgs e)
{
result.Text = "0";
equation.Text = "";
button_dot = false;
}
private void buttonC_Click(object sender, EventArgs e)
{
result.Clear();
value = 0;
}
private void buttonEqual_Click(object sender, EventArgs e)
{
equation.Text = "";
button_dot = false;
operation_pressed = true;
if (operation != "")
result.Text = class1.GetResult(operation, value, result.Text);
else
result.Text = result.Text + "";
}
private void buttonDot_Click(object sender, EventArgs e)
{
Button b = (Button)sender;
if ((!button_dot && !operation_pressed) || result.Text == "0")
result.Text = result.Text + b.Text;
button_dot = true;
}
}
}
You don't need to append keychar in your result.Text (Assuming result is your TextBox item) as you have written in line result.Text += e.KeyChar.ToString();. That's the line which is doubling your input.
Remove it and it'll work as expected.
I'd change it from keypress to KeyUp instead. That way it only fires as soon as the key is released.
Edit: Check out this info: Difference between the KeyDown Event, KeyPress Event and KeyUp Event in Visual Studio

C# Calculator working incorrectly [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
The calculator works fine if I keep using the same operator(*, /, +, -) but if for example I decide to multiply the total of two added numbers it'll give me a wrong answer. I've looked for a solution but can't seem to find one.
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
bool multiply = false;
bool divide = false;
bool add = false;
bool subtract = false;
private void btnOne_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + "1";
}
private void btnTwo_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + "2";
}
private void btnThree_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + "3";
}
private void btnFour_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + "4";
}
private void btnFive_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + "5";
}
private void btnSix_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + "6";
}
private void btnSeven_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + "7";
}
private void btnEight_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + "8";
}
private void btnNine_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + "9";
}
private void btnZero_Click(object sender, EventArgs e)
{
if (txtDisplay.Text.Length > 0)
{
txtDisplay.Text = txtDisplay.Text + "0";
}
}
private void btnClear_Click(object sender, EventArgs e)
{
txtDisplay.Clear();
}
private void btnDecimalPoint_Click(object sender, EventArgs e)
{
if (txtDisplay.Text.Contains("."))
{
return;
}
else
{
txtDisplay.Text = txtDisplay.Text + ".";
}
}
private void btnNegative_Click(object sender, EventArgs e)
{
if (txtDisplay.Text.Contains("-"))
{
txtDisplay.Text = txtDisplay.Text.Remove(0,1);
}
else
{
txtDisplay.Text = "-" + txtDisplay.Text;
}
}
private void btnMultiply_Click(object sender, EventArgs e)
{
if (txtDisplay.Text == "")
{
return;
}
else
{
multiply = true;
txtDisplay.Tag = txtDisplay.Text;
txtDisplay.Text = "";
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
if (txtDisplay.Text == "")
{
return;
}
else
{
add = true;
txtDisplay.Tag = txtDisplay.Text;
txtDisplay.Text = "";
}
}
private void btnSubtract_Click(object sender, EventArgs e)
{
if (txtDisplay.Text == "")
{
return;
}
else
{
subtract = true;
txtDisplay.Tag = txtDisplay.Text;
txtDisplay.Text = "";
}
}
private void btnEquals_Click(object sender, EventArgs e)
{
if (multiply)
{
decimal dec = Convert.ToDecimal(txtDisplay.Tag) * Convert.ToDecimal(txtDisplay.Text);
txtDisplay.Text = dec.ToString();
}
if (divide)
{
decimal dec = Convert.ToDecimal(txtDisplay.Tag) / Convert.ToDecimal(txtDisplay.Text);
txtDisplay.Text = dec.ToString();
}
if (add)
{
decimal dec = Convert.ToDecimal(txtDisplay.Tag) + Convert.ToDecimal(txtDisplay.Text);
txtDisplay.Text = dec.ToString();
}
if (subtract)
{
decimal dec = Convert.ToDecimal(txtDisplay.Tag) - Convert.ToDecimal(txtDisplay.Text);
txtDisplay.Text = dec.ToString();
}
else
{
return;
}
}
private void btnDivide_Click(object sender, EventArgs e)
{
if (txtDisplay.Text == "")
{
return;
}
else
{
divide = true;
txtDisplay.Tag = txtDisplay.Text;
txtDisplay.Text = "";
}
}
}
It looks like the problem is that you aren't clearing your operation commands. i.e. you set it to Add, but you never clear the Add when you set it to Multiply. If you look in the btnEquals_Click method, it's possible to have several operations active at once, and it will execute all of them.
Look at your btnEquals_Click event. Someone chooses to add, so add = true and it's the only if block that executes - everything good so far.
Then someone chooses to multiply, so now multiply = true, but add = true as well, so now you're multiplying and adding. If someone goes through all the operators, then (because you're never clearing your operator flags), every number thereafter will be multiplied, then divided, then added, and finally subtracted.
To fix it, you could create a method that clears the operators:
private void ResetOperatorFlags()
{
multiply = false;
divide = false;
add = false;
subtract = false;
}
Then call it before you perform an operation on the number:
private void btnMultiply_Click(object sender, EventArgs e)
{
if (txtDisplay.Text == "")
return;
ResetOperatorFlags();
multiply = true;
txtDisplay.Tag = txtDisplay.Text;
txtDisplay.Text = "";
}
Finally, in your btnEquals_Click event, use else if... you won't really need it after clearing the flags, but there's no sense in testing every flag if only one can be set at a time:
private void btnEquals_Click(object sender, EventArgs e)
{
if (multiply)
{
...
}
else if (divide)
{
...

Categories