Zigma
Zigma

Reputation: 529

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

Upvotes: 1

Views: 858

Answers (3)

Qasim Javaid Khan
Qasim Javaid Khan

Reputation: 660

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

Upvotes: 2

Zigma
Zigma

Reputation: 529

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.

Upvotes: 0

RBarryYoung
RBarryYoung

Reputation: 56785

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 ...

Upvotes: 1

Related Questions