I'm trying to write a caculator as a website,
I set 2 variables in my class to store the number,
but everytime I click a "+" or "-" button,
the variable go back to the inital stamtement.
Here is my code:
public partial class _Default : System.Web.UI.Page
{
int choice = 0;
Boolean caluOrNot = false;
double before, after;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Btn1_Click(object sender, EventArgs e)
{
if (this.caluOrNot == false)
{
if (txtResult.Text.ToString() == "0")
{
txtResult.Text = "1";
}
else
{
txtResult.Text += "1";
}
}
else
{
txtResult.Text = "1";
}
}
protected void Btn2_Click(object sender, EventArgs e)
protected void Btn3_Click(object sender, EventArgs e)
protected void Btn4_Click(object sender, EventArgs e)
protected void Btn5_Click(object sender, EventArgs e)
protected void Btn6_Click(object sender, EventArgs e)
protected void Btn7_Click(object sender, EventArgs e)
protected void Btn8_Click(object sender, EventArgs e)
protected void Btn9_Click(object sender, EventArgs e)
protected void Btn0_Click(object sender, EventArgs e)
protected void BtnPoint_Click(object sender, EventArgs e)
{
txtResult.Text += ".";
}
protected void BtnJia_Click(object sender, EventArgs e)
{
this.choice = 1;
this.caluOrNot = true;
before = Double.Parse(txtResult.Text.ToString());
txtCalu.Text = before.ToString() + "+";
}
protected void BtnJen_Click(object sender, EventArgs e)
protected void BtnCheng_Click(object sender, EventArgs e)
protected void BtnChu_Click(object sender, EventArgs e)
protected void btnClear_Click(object sender, EventArgs e)
{
txtResult.Text = "0";
this.choice = 0;
}
protected void btnGo_Click(object sender, EventArgs e)
{
double a;
switch (this.choice)
{
case 1:
a = before + after;
txtResult.Text = a.ToString();
break;
case 2:
a = before - after;
txtResult.Text = a.ToString();
break;
case 3:
a = before * after;
txtResult.Text = a.ToString();
break;
case 4:
a = before / after;
txtResult.Text = a.ToString();
break;
default:
break;
}
}
}
As th code, everytime I click btnJia will trigger the onclick method BtnJia_Click
The choice will be set to "1" and caculOrNot set to true, but the values change back to 0 and false when the BtnJia_Click finish.
How can I solve it?
In ASP.NET when you click BtnJia_Click everything starts from beginning. So you need to store values of caculOrNot and choice at session and read them from session when you need them. Here is an example:
protected void BtnJia_Click(object sender, EventArgs e)
{
this.choice = 1;
this.caluOrNot = true;
before = Double.Parse(txtResult.Text.ToString());
txtCalu.Text = before.ToString() + "+";
//Store them in Session
Session["choice"] = this.choice;
Session["caluOrNot"] = this.caluOrNot;
}
protected void btnGo_Click(object sender, EventArgs e)
{
// Read them from Session when you need
if(Session["choice"] != null)
{
this.choice = Convert.ToInt32(Session["choice"]);
}
double a;
switch (this.choice)
{
case 1:
a = before + after;
txtResult.Text = a.ToString();
break;
case 2:
a = before - after;
txtResult.Text = a.ToString();
break;
case 3:
a = before * after;
txtResult.Text = a.ToString();
break;
case 4:
a = before / after;
txtResult.Text = a.ToString();
break;
default:
break;
}
}
}
Read more about Session State here.
Related
For some reason when I test the code the minus if statement adds the two values togehther instead of minusing them, along with that the other if statements for times and subtraction return the error message
System.FormatException: 'Input string was not in a correct format.'
The first if statement for addition works fine despite this
public Form1()
{
InitializeComponent();
}
private void Calculation()
{
decimal answer;
if (savedOperator == "+")
{
answer = savedNumber + Convert.ToDecimal(txtBox.Text);
txtBox.Text = answer.ToString();
savedOperator = "";
}
if (savedOperator == "-")
{
answer = savedNumber - Convert.ToDecimal(txtBox.Text);
txtBox.Text = answer.ToString();
savedOperator = "";
}
if (savedOperator == "*")
{
answer = savedNumber * Convert.ToDecimal(txtBox.Text);
txtBox.Text = answer.ToString();
savedOperator = "";
}
if (savedOperator == "/")
{
answer = savedNumber / Convert.ToDecimal(txtBox.Text);
txtBox.Text = answer.ToString();
savedOperator = "";
}
}
private void SaveNumber()
{
savedNumber = System.Convert.ToDecimal(txtBox.Text);
txtUpperBox.Text = savedNumber.ToString();
}
// numbers
private void btn1_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + "1";
}
private void btn2_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + "2";
}
private void btn3_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + "3";
}
private void btn4_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + "4";
}
private void btn5_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + "5";
}
private void btn6_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + "6";
}
private void btn7_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + "7";
}
private void btn8_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + "8";
}
private void btn9_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + "9";
}
private void btn0_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + "0";
}
// operators
private void btnPlus_Click(object sender, EventArgs e)
{
SaveNumber();
txtBox.Clear();
savedOperator = "+";
txtBox.Text = "+";
}
private void btnMinus_Click(object sender, EventArgs e)
{
SaveNumber();
txtBox.Clear();
savedOperator = "-";
txtBox.Text = "-";
}
private void btnTimes_Click(object sender, EventArgs e)
{
SaveNumber();
txtBox.Clear();
savedOperator = "*";
txtBox.Text = "*";
}
private void btnDivide_Click(object sender, EventArgs e)
{
SaveNumber();
txtBox.Clear();
savedOperator = "/";
txtBox.Text = "/";
}
private void btnEquals_Click(object sender, EventArgs e)
{
Calculation();
}
}
}
I don't see any obvious problems in your math logic.
I tested it in https://dotnetfiddle.net/Uo2EHM and it works fine. The issue could be in the inputs you are getting or in conversion.
You can either set breakpoints at various points in your code to see what the values are or print out the values to another "debug" text box.
Some potential issues I see are in conversion between number and string. Sometimes, it may not give you the results you expect.
Also, you might want to use a switch statement instead of multiple if statements but that is not a bug you are seeing.
Could the issue be with the value of the TextBox before the calculations are performed? If you have "8--3" it would be the same as 8 - (-3). Try your code with different text boxes for the numbers and the operators to see if the problem occurs.
I have been tasked to create a calculator on a C# web application, however I noticed that when I use variables set in other buttons, the programs sets them to 0, specifically the 'num' and 'sign' variable which I assigned in the PlusBut but when actually using them in the EqualBut they are assigned to 0. My code works in a windows form but this is my first time using website application.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1 {
public partial class About: System.Web.UI.Page {
int sign;
double num, num2;
protected void Page_Load(object sender, EventArgs e) { }
protected void Button4_Click(object sender, EventArgs e) { }
protected void But0_Click(object sender, EventArgs e) {
AnswerBox.Text = AnswerBox.Text + "0";
}
protected void But1_Click(object sender, EventArgs e) {
AnswerBox.Text = AnswerBox.Text + "1";
}
protected void But2_Click(object sender, EventArgs e) {
AnswerBox.Text = AnswerBox.Text + "2";
}
protected void But3_Click(object sender, EventArgs e) {
AnswerBox.Text = AnswerBox.Text + "3";
}
protected void But4_Click(object sender, EventArgs e) {
AnswerBox.Text = AnswerBox.Text + "4";
}
protected void But5_Click(object sender, EventArgs e) {
AnswerBox.Text = AnswerBox.Text + "5";
}
protected void But6_Click(object sender, EventArgs e) {
AnswerBox.Text = AnswerBox.Text + "6";
}
protected void But7_Click(object sender, EventArgs e) {
AnswerBox.Text = AnswerBox.Text + "7";
}
protected void But8_Click(object sender, EventArgs e) {
AnswerBox.Text = AnswerBox.Text + "8";
}
protected void But9_Click(object sender, EventArgs e) {
AnswerBox.Text = AnswerBox.Text + "9";
}
protected void PlusBut_Click(object sender, EventArgs e) {
num = double.Parse(AnswerBox.Text);
AnswerBox.Text = "";
sign = 1;
}
protected void DecBut_Click(object sender, EventArgs e) {
AnswerBox.Text = AnswerBox.Text + ".";
}
protected void MinusBut_Click(object sender, EventArgs e) {
num = double.Parse(AnswerBox.Text);
AnswerBox.Text = "";
sign = 2;
}
protected void MultBut_Click(object sender, EventArgs e) {
num = double.Parse(AnswerBox.Text);
AnswerBox.Text = "";
sign = 3;
}
protected void DivButton_Click(object sender, EventArgs e) {
num = double.Parse(AnswerBox.Text);
AnswerBox.Text = "";
sign = 4;
}
protected void EqualBut_Click(object sender, EventArgs e) {
num2 = double.Parse(AnswerBox.Text);
AnswerBox.Text = "" + num + " " + num2 + " " + sign;
}
}
}
Essentially when you trigger a postback (by clicking a button in your case), a new instance of the About class is created and the previous values of your fields are lost.
You should read about ASP Page Life Cycle Events.
There are multiple approaches to making variables persistent, one is to use Session or ViewState variables, which is probably the simplest solution in your case and should be sufficient for a calculator.
double num1
{
get { return Convert.ToDouble(ViewState["num1"] ?? 0); }
set { ViewState["num1"] = value; }
}
Another approach would be to use JavaScript to avoid postbacks, however that would increase the complexity of your app by combining client side and server side actions.
I'm guessing a bit, but I think your problem is that web applications don't persist from one button press to another. Every time the user presses a button, the browser sends a request to the server. The server creates the web application and gives it the request, and the application produces the result.
You need to persist values from one request to the next. There are several ways to do this, but it's normal to save them to a session. The exact implantation depends on what web technology you're using.
ASP.NET is server side. So each time a click is triggered at client side a new instance of About is created and sign, num and num2 are created with default value (aka 0).
Either change to a client side programming language as JavaScript or define the values as static. Static variables are linked to the class and not an instance of it, so they will hold the value between callbacks:
public partial class About : System.Web.UI.Page
{
static int sign;
static double num;
static double num2;
/* ... */
protected void PlusBut_Click(object sender, EventArgs e)
{
About.num = double.Parse(AnswerBox.Text);
AnswerBox.Text = "";
sign = 1;
}
}
I created a basic calculator, but each time I enter the second value and press the equal button, I get no result back. Only the value I entered 2nd.
My methods for +-*/ are in a separate class. What will the best way be to resolve this problem? It is probably a simple error, but I can't find it. Can you also please give me an explanation on what I did wrong. Thanks in Advance.
public sealed partial class Calculator : Page
{
public double num01, num02;
int operater;
public Calculator()
{
this.InitializeComponent();
}
private void btn1_Click(object sender, RoutedEventArgs e)
{
txtcalcdisplay.Text =txtcalcdisplay.Text+ "1";
}
private void btn2_Click(object sender, RoutedEventArgs e)
{
txtcalcdisplay.Text = txtcalcdisplay.Text + "2";
}
private void btn3_Click(object sender, RoutedEventArgs e)
{
txtcalcdisplay.Text = txtcalcdisplay.Text + "3";
}
private void btn4_Click(object sender, RoutedEventArgs e)
{
txtcalcdisplay.Text = txtcalcdisplay.Text + "4";
}
private void btn5_Click(object sender, RoutedEventArgs e)
{
txtcalcdisplay.Text = txtcalcdisplay.Text + "5";
}
private void btn6_Click(object sender, RoutedEventArgs e)
{
txtcalcdisplay.Text = txtcalcdisplay.Text + "6";
}
private void btn7_Click(object sender, RoutedEventArgs e)
{
txtcalcdisplay.Text = txtcalcdisplay.Text + "7";
}
private void btn8_Click(object sender, RoutedEventArgs e)
{
txtcalcdisplay.Text = txtcalcdisplay.Text + "8";
}
private void btn9_Click(object sender, RoutedEventArgs e)
{
txtcalcdisplay.Text = txtcalcdisplay.Text + "9";
}
private void Clear_Click(object sender, RoutedEventArgs e)
{
txtcalcdisplay.Text = string.Empty;
}
private void btnsubtract_Click(object sender, RoutedEventArgs e)
{
num01 = Convert.ToDouble(txtcalcdisplay.Text);
txtcalcdisplay.Text = "";
operater = '1';
}
private void btnadd_Click(object sender, RoutedEventArgs e)
{
num01 = Convert.ToDouble(txtcalcdisplay.Text);
txtcalcdisplay.Text = "";
operater = '2';
}
private void btnmultiply_Click(object sender, RoutedEventArgs e)
{
num01 = Convert.ToDouble(txtcalcdisplay.Text);
txtcalcdisplay.Text = "";
operater = '3';
}
private void btndivide_Click(object sender, RoutedEventArgs e)
{
num01 = Convert.ToDouble(txtcalcdisplay.Text);
txtcalcdisplay.Text = "";
operater = '4';
}
private void btnequals_Click(object sender, RoutedEventArgs e)
{
switch (operater)
{
case 1:
num02 = Convert.ToDouble(txtcalcdisplay.Text);
CalculationClass sub = new CalculationClass();
double answer= sub.Subtract(num01, num02);
txtcalcdisplay.Text = answer.ToString();
break;
case 2:
num02 = Convert.ToDouble(txtcalcdisplay.Text);
CalculationClass add = new CalculationClass();
answer= add.Addition(num01, num02);
txtcalcdisplay.Text = answer.ToString();
break;
case 3:
num02 = Convert.ToDouble(txtcalcdisplay.Text);
CalculationClass mult = new CalculationClass();
answer = mult.Multiply(num01, num02);
txtcalcdisplay.Text = answer.ToString();
break;
case 4:
num02 = Convert.ToDouble(txtcalcdisplay.Text);
CalculationClass div = new CalculationClass();
answer = div.Div(num01, num02);
txtcalcdisplay.Text = Convert.ToString(answer);
break;
}
}
private void btnback_Click(object sender, RoutedEventArgs e)
{
}
private void btnplusdivideminus_Click(object sender, RoutedEventArgs e)
{
}
private void btncomma_Click(object sender, RoutedEventArgs e)
{
}
private void btngallery_Click(object sender, RoutedEventArgs e)
{
}
private void btncontact_Click(object sender, RoutedEventArgs e)
{
}
private void num0_Click(object sender, RoutedEventArgs e)
{
txtcalcdisplay.Text += "0";
num01 = Convert.ToDouble(txtcalcdisplay.Text);
}
}
class CalculationClass
{
double answer;
public double Addition(double x, double y)
{
answer = x + y;
return answer;
}
public double Subtract(double x, double y)
{
answer = x - y;
return answer;
}
public double Multiply(double x, double y)
{
answer = x * y;
return answer;
}
public double Div(double x, double y)
{
answer = x / y;
return answer;
}
}
I'm not 100% certain, but I'm fairly sure this has to do with the fact that your variable operater is an int but you're assigning a character to it (this works - characters can be assigned to ints) and then comparing it back to the integer (eg doing 1 == '1')
int x = '1';
Console.WriteLine(x); // outputs 49
Console.WriteLine(x == 1); // outputs false
So to fix it either use the characters in your switch:
switch(operater){
case '1': ...
}
Or assign the integer 1,2,3,4 rather than the character '1','2,'3','4'
private void btnadd_Click(object sender, RoutedEventArgs e)
{
num01 = Convert.ToDouble(txtcalcdisplay.Text);
txtcalcdisplay.Text = "";
operater = 2; // here
}
So in your operator click handlers (the ones for +,-,*,/ etc.) you are setting your operater variable to a character '1','2', etc. Well, your operater variable is an int. But wait, you shouldn't be able to assign a char to an int?! Well, the compiler does an implicit conversion here (language spec says it should).
So what ends up happening when you do operater = '1' is that operater gets assigned 49 ('1''s ASCII value). Then when you get to your equals button click handler it hits that switch statement. And guess what? You don't have a case for 49. So nothing happens and you keep seeing your second number as the text on screen.
So to fix it, remove the single quotes around your numbers you assign to operater in your operator handlers. IE:
private void btnsubtract_Click(object sender, RoutedEventArgs e)
{
num01 = Convert.ToDouble(txtcalcdisplay.Text);
txtcalcdisplay.Text = "";
operater = 1; // <-- change this line to be like this, removed the single quotes
}
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)
{
...
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.