Keep data after form submit / page reload

Reply Forum
Forum postRedBird @ 2009-02-19 03:11:25
ReplyReply to
Hi,
well let me try to reduce my problem to the main point...

I have this page with two buttons.
In the code behind I have a global boolean variable.

Now if I press button one, it sets the boolean to true.
And if I press button two afterwards, it tells me that my variable is false (that seems to be the standard value after initializing).

public partial class _Default : System.Web.UI.Page 
{
    bool clicked;
    protected void Button1_Click(object sender, EventArgs e)
    {
        clicked = true;
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        if (clicked)
            Button2.Text = "clicked";
        else Button2.Text = "click me";
    }
}


Am I overlooking something really simplistic here, or is it not possible to keep data after a page submit???

Of course I could keep a boolean value in a not rendered control or with a tonne of other ways, but that's not really a clean way of coding, is it?

Well hopfully you can tell me where I went on the wrong path with my thinking process. I really feel like a fool at the moment, not being able to use a simple boolean :(


Forum postWebmaster @ 2009-02-19 08:36:11
ReplyReply to
Hi,

Actually, that's simply how it works. Your variables are initialized on each request to the page. In this case, you haven't defined a default value for your boolean variable, so it's automatically initialized to false, which is the default :). Now, if you wish to save a variable for the next request, there are, as you say your self, a bunch of way. I prefer using the ViewState, if it's a variable local to the page, which it usually is. If not, you could use a Session variable. ASP.NET uses the ViewState it self, when saving various control values between post backs :)


Forum postRedBird @ 2009-02-19 11:04:00
ReplyReply to
Pity, I had hoped there was a more elegant solution. Thx anyway.

Are those tutorials yours? They are great, but perhaps you could make the 'next' button a bit easier to find. Took me ages to find it :D


Forum postWebmaster @ 2009-04-16 08:06:07
ReplyReply to
Done! Is it better now? :)











© net-tutorials.com 2006 - 2012

MailContact net-tutorials.com