简体   繁体   中英

Why can't I get the value from textbox?

I've just started learning ASP.NET and I'm facing a problem with getting textbox values. I want to do a simple calculator with only 4 basic operations but what happens is that after I click the + sign and click Go, I see that I didn't store the first number at all. Second number is fine though. Here is a sample of my code.

public partial class deafult : System.Web.UI.Page
{
    public TextBox output = new TextBox();
    public double temp,tempAdd, calc;

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        tempAdd = Convert.ToDouble(output.Text);
        output.Text = String.Empty;
    }
    //User enters another number after clicking Add button then clicks Proc
    protected void proc_Click(object sender, EventArgs e)
    {
        temp = Convert.ToDouble(output.Text);
        calc = tempAdd + temp;
        output.Text = calc.ToString();
    }
}

I debugged and tempAdd is always 0 but I get the number in temp. temp variables and calc is defined public.

You essentially have the problem with all of your variables being re-initialized on load of the page. Unlike winforms, web is stateless .

There are ways of persisting state between refreshes, however. The most obvious choice for your application would be to only go to the server once with the both values and what you want to do with them. ie One button click.

However, for personal edification, it may be worth looking up ViewState . This allows you to store values in an array of sorts and retrieve them even after a refresh.

There are also Session and Application level arrays in ASP.NET that work in similar ways.

Every time you call the page (by events) all your properties is initialized. Try to do all your logic in one event or store your properties in manager / service / db.

In web (Asp.Net) on every postback properties will get cleared, try to use ViewState or Session variables to hold these values. Refer Asp.Net State Management concepts from MS.

Hope this may help you.

Web controls are State less so you should user session sate to hold the first value then do your stuff...

Ex:-

 protected void btnAdd_Click(object sender, EventArgs e)
    {
        Session["tempAdd"] = output.Text;
        output.Text = String.Empty;
    }

    protected void proc_Click(object sender, EventArgs e)
    {
        temp = Convert.ToDouble(output.Text);
        string oldval=Session["tempAdd"] != null ?Session["tempAdd"].ToString() :"";
         if(oldval!="")
          tempadd=Convert.ToDouble(oldval);

        calc = tempAdd + temp;
        output.Text = calc.ToString();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM