Double result when using keypress - c#

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

Related

facing problem in c# calculator operator pressed it shows calculates result while pressing another operator

I am new to c# programming.I am building a simple calculator but when i add two numbers and press operator(+) button it adds two numbers but when i again press another operator it just adds the previous value like 2+2= 4 and if i press (-) operator after that it just shows result = 8 , please help me to get out of this.
thanks.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Calculator
{
public partial class Form1 : Form
{
double value = 0;
string operation = "";
bool opt_pressed = false;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if ((txtMain.Text == "0") || (opt_pressed))
txtMain.Clear();
Button a = (Button)sender;
opt_pressed = false;
if (a.Text == ".")
{
if (!txtMain.Text.Contains("."))
txtMain.Text = txtMain.Text + a.Text;
}
else
{
txtMain.Text = txtMain.Text + a.Text;
}
}
private void txtMain_TextChanged(object sender, EventArgs e)
{
}
private void button10_Click(object sender, EventArgs e)
{
txtMain.Clear();
value = 0;
label1.Text = "";
}
private void button11_Click(object sender, EventArgs e)
{
Button b = (Button)sender;
if (value != 0)
{
equal.PerformClick();
operation = b.Text;
label1.Text = value + " " + operation;
opt_pressed = true;
}
else
{ operation = b.Text;
value = double.Parse(txtMain.Text);
label1.Text = value + " " + operation;
opt_pressed = true;
}
}
private void button16_Click(object sender, EventArgs e)
{
switch (operation)
{
case "+":
txtMain.Text = (value + double.Parse(txtMain.Text)).ToString();
break;
case "-":
txtMain.Text = (value - double.Parse(txtMain.Text)).ToString();
break;
case "/":
txtMain.Text = (value / double.Parse(txtMain.Text)).ToString();
break;
case "*":
txtMain.Text = (value * double.Parse(txtMain.Text)).ToString();
break;
}
value = double.Parse(txtMain.Text);
label1.Text = "";
}
private void label1_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, KeyPressEventArgs e)
{
Button a = (Button)sender;
button1.PerformClick();
operation = a.Text;
}
}
}

Output append with input in C#

I am creating a Calculator in C# windows form and after performing operation(+,-,*,/) the output of the operation append with the input of the next operation!
This is the result of adding 33 in 33
After pressing equal its gets 66 and when further input such as 33 is added input is appended to previous output
This is the code i have written so far..
public Calculator()
{
InitializeComponent();
}
private void btn_click(object sender, EventArgs e)
{
if (( txtResult.Text == "0")||(operation_pressed))
txtResult.Clear();
Button b = (Button)sender;
txtResult.Text = txtResult.Text + b.Text;
operation_pressed = false;
}
private void btnPoint_Click(object sender, EventArgs e)
{
Button b = (Button)sender;
if (b.Text == ".")
{
if (!txtResult.Text.Contains("."))
{
txtResult.Text = txtResult.Text + b.Text;
}
}
else
{
txtResult.Text = txtResult.Text + b.Text;
}
}
private void operator_click(object sender, EventArgs e)
{
Button b = (Button)sender;
operation = b.Text;
value = Double.Parse(txtResult.Text);
operation_pressed = true;
}
private void btnClear_Click(object sender, EventArgs e)
{
txtResult.Text = "0";
}
private void btnC_Click(object sender, EventArgs e)
{
txtResult.Clear();
value = 0d;
}
private void btnEqual_Click(object sender, EventArgs e)
{
switch (operation)
{
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;
default:
break;
}
operation_pressed = false;
operation = "";
}
The text is appending to the existing value because of this line in the btn_click event
txtResult.Text = txtResult.Text + b.Text;
Earlier in this event, you are checking the value of operation_pressed before calling txtResult.Clear();, however you are setting this to false in the btnEqual_Click event.
Removing that line so that operation_pressed remains true after = is pressed would then clear the result on next button press.
On a side note, you will be better off storing the value in a variable, rather than parsing txtResult to double each time.

Change Label's Text when Button is clicked

I am new to C#. I need the text of lblBalance to remain as it is when the btnNew is clicked, while it changes according to some calculatios when btnCalc is clicked. Here is my attempt so far.
FIGURED IT OUT, Thanks!
private void btnReset_Click(object sender, EventArgs e)
{
//Reset balance to 0.
balance = 0m;
lblBalance.Text = "";
tbDate.Text = "";
//Call the setupForm procedure.
setupForm();
}
private void setupForm()
{
//Setupform done once to reduce amount of times code must be entered.
//Code to clear these entries and set radio and checkboxes to false.
tbDate.Text = "";
tbAmount.Text = "";
rDeposit.Checked = false;
rWithdrawal.Checked = false;
rFee.Checked = false;
chkBank.Checked = false;
//Return focus to the date textbox
tbDate.Focus();
}
private void btnNew_Click(object sender, EventArgs e)
{
//Clear form, but retain balance when clicked.
setupForm();
}
private void tbDate_TextChanged(object sender, EventArgs e)
{
}
private void lblBalance_Click(object sender, EventArgs e)
{
}
private void btnCalc_Click(object sender, EventArgs e)
{
decimal Amount;
Amount = decimal.Parse(tbAmount.Text);
if ((rDeposit.Checked == true) && (chkBank.Checked == true))
{
Decimal.TryParse(lblBalance.Text, out balance);
lblBalance.Text = Convert.ToString(balance + Amount);
}
else if ((rWithdrawal.Checked == true) && (chkBank.Checked == true))
{
Decimal.TryParse(lblBalance.Text, out balance);
lblBalance.Text = Convert.ToString(balance - Amount);
}
else if ((rFee.Checked == true) && (chkBank.Checked == true))
{
Decimal.TryParse(lblBalance.Text, out balance);
lblBalance.Text = Convert.ToString(balance - Amount);
}
if ((rDeposit.Checked == false) && (rWithdrawal.Checked == false) && (rFee.Checked == false))
{
MessageBox.Show("ERROR: You must select Deposit, Withdrawal, or Service Fee.");
}
}
private void rDeposit_CheckedChanged(object sender, EventArgs e)
{
}
}
}
change:
lblBalance.Text += balance.ToString();
to
lblBalance.Text = balance.ToString();
Inside your btnNew_Click event

Keeping variable values

I am in in study phase of asp.net so decided to do an online calculator. The issue is when i do a calculation 1 + 5 = it does not give any output at all. I tried a debugging.
Click button 1 :
first value = 1;
click button + :
first value = null;
click button 5 :
first value = 5
click button =
NOTHING :)
Here is my c# code :
public partial class _Default : System.Web.UI.Page
{
string firstOperand;
string secondOperand;
string Operator;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnOff_Click(object sender, EventArgs e)
{
txtScreen.Enabled = false;
ClearVariables();
}
protected void btnOn_Click(object sender, EventArgs e)
{
txtScreen.Enabled = true;
ClearVariables();
}
private void ClearVariables()
{
firstOperand = "";
secondOperand = "";
Operator = "";
}
protected void Operand(string value)
{
if (value == null) return;
try
{
txtScreen.Text = value;
if (firstOperand == null)
{
firstOperand = value;
}
else
{
if (Operator == null)
{
firstOperand.Insert(firstOperand.Length, value);
}
else
{
secondOperand.Insert(secondOperand.Length, value);
}
}
}
catch (Exception ex)
{
}
}
protected void Num1_Click(object sender, EventArgs e)
{
txtScreen.Text = Num1.Text;
Operand(Num1.Text);
}
protected void Num2_Click(object sender, EventArgs e)
{
txtScreen.Text = Num2.Text;
Operand(Num2.Text);
}
protected void Num3_Click(object sender, EventArgs e)
{
txtScreen.Text = Num3.Text;
Operand(Num3.Text);
}
protected void Num4_Click(object sender, EventArgs e)
{
txtScreen.Text = Num4.Text;
Operand(Num4.Text);
}
protected void Num5_Click(object sender, EventArgs e)
{
txtScreen.Text = Num5.Text;
Operand(Num5.Text);
}
protected void Num6_Click(object sender, EventArgs e)
{
txtScreen.Text = Num6.Text;
Operand(Num6.Text);
}
protected void Num7_Click(object sender, EventArgs e)
{
txtScreen.Text = Num7.Text;
Operand(Num7.Text);
}
protected void Num8_Click(object sender, EventArgs e)
{
txtScreen.Text = Num8.Text;
Operand(Num8.Text);
}
protected void Num9_Click(object sender, EventArgs e)
{
txtScreen.Text = Num9.Text;
Operand(Num9.Text);
}
protected void Num0_Click(object sender, EventArgs e)
{
txtScreen.Text = Num0.Text;
Operand(Num0.Text);
}
protected void btnClr_Click(object sender, EventArgs e)
{
txtScreen.Text = "";
ClearVariables();
}
protected void OpDiv_Click(object sender, EventArgs e)
{
if (firstOperand != null)
{
txtScreen.Text = "";
Operator = OpDiv.Text;
}
}
protected void OpMul_Click(object sender, EventArgs e)
{
if (firstOperand != null)
{
txtScreen.Text = "";
Operator = OpMul.Text;
}
}
protected void OpSub_Click(object sender, EventArgs e)
{
if (firstOperand != null)
{
txtScreen.Text = "";
Operator = OpSub.Text;
}
}
protected void OpAdd_Click(object sender, EventArgs e)
{
if (firstOperand != null)
{
txtScreen.Text = "";
Operator = OpAdd.Text;
}
}
protected void OpEqual_Click(object sender, EventArgs e)
{
if (firstOperand == null && Operator == null)
{
return;
}
else if (firstOperand != null && Operator != null && secondOperand == null)
{
secondOperand = firstOperand;
}
else
{
double num1;
double num2;
try
{
num1 = Double.Parse(firstOperand);
num2 =Double.Parse(secondOperand);
{
switch (Operator)
{
case "+":
num1 += num2;
firstOperand = num1.ToString();
txtScreen.Text = firstOperand;
break;
case "-":
num1 -= num2;
firstOperand = num1.ToString();
txtScreen.Text = firstOperand;
break;
case "/":
if (num2 == 0)
{
txtScreen.Text = "Divison by zero";
}
else
{
num1 /= num2;
firstOperand = num1.ToString();
txtScreen.Text = firstOperand;
}
break;
case "*":
num1 *= num2;
firstOperand = num1.ToString();
txtScreen.Text = firstOperand;
break;
default: txtScreen.Text = "Invalid Operation";
break;
}
}
}
catch (Exception ex)
{
txtScreen.Text = "Not a valid Number";
ClearVariables();
}
}
ClearVariables();
}
protected void OpDot_Click(object sender, EventArgs e)
{
if (firstOperand != null)
{
if (Operator == null)
{
firstOperand.Insert(firstOperand.Length, ".");
}
else
{
secondOperand.Insert(secondOperand.Length, ".");
}
}
}
}
Could someone explain what is happening? And how to resolve the same.
Thanks
OK. Its simple here, your values are refreshing on postback. so simply hold the values in viewstate.
And before that do reduce your code lines.
you have
protected void Num5_Click(object sender, EventArgs e)
{
txtScreen.Text = Num5.Text;
Operand(Num5.Text);
}
arround 10 events like this. so do first make it a single event like
protected void Num_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
txtScreen.Text = btn.Text;
Operand(btn.Text);
}
and assign this event as Click event for every numeric button
Now in Operand Method make something like
private void Operand(string value)
{
if(ViewState["FirstOperand"] == null)
ViewState["FirstOperand"] = value;
else if(ViewState["SecondOperand"] == null)
ViewState["SecondOperand"] = value;
}
similarly reduce you code for add, sub, mul, divide operator click events as i just showed above for numeric button click events.
and also set the operator value in ViewState["Operator"].
and finally in your OpEqual_Click event. initally set first and second operand like
if(ViewState["FirstOperand"] != null)
firstOperand = ViewState["FirstOperand"].ToString();
if(ViewState["SecondOperand"] != null)
secondOperand = ViewState["SecondOperand"].ToString();
if(ViewState["Operator"] != null)
Operator = ViewState["Operator"].ToString();
Hope this helps
It appears to me that your problem is in your ASP.Net environment and/or your IDE, rather than in your code. I do not know ASP.Net well, but it I do know C# and I notice these two odd facts:
Your debugging shows firstOperand being reset to null or the current operand after every event.
But, you code never sets firstOperand to null. It does set it to the empty string("") in clearVariables, but that is not the same as null ("" != null).
Therefore, I must conclude that something other than your code is setting firstOperand to null. The most logical source of that would be your execution/debugging environment which does reset all object and string variables to null when it initializes for execution, or when it invokes a new Page, Class, Method, etc. (for any variable scoped to those).
Of course you don't want it to do that for every button click, so I have to assume that there is something set wrong in your environment/setup that is causing this.
Hopefully, someone who knows ASP.Net better then I do can explain the rest ...
Yes At last I found it.
It is the problem with sessions. Every time I click button, a new session invokes and all the value resets. So We need to add values in session and recover it.
Like :
Session["Calc"] = firstOperand + ",";
Session["Calc"] += secondOperand + ",";
Session["Calc"] += Operator + ",";
and at page load:
try
{
var Data = Session["Calc"].ToString().Split(',');
if(Data[0] != "")
firstOperand = Data[0];
if (Data[1] != "")
Operator = Data[1];
if (Data[2] != "")
secondOperand = Data[2];
}
catch(Exception ex)
{
}
It is not a good solution I think(still studying asp :) ). And I can use if condition since number of item is fixed to 3.

C# Calculator - textBox to listBox

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);
}

Categories