Link to home
Start Free TrialLog in
Avatar of brooklynDev
brooklynDev

asked on

How can I get page variable values to persist accross postbacks?

I heard a developer tell me asp.net page variables persisted across postbacks, but I haven’t ever seen this work, can it?

so if I have a page like so:

namespace blah
{
      public class page : System.Web.UI.Page
      {
            protected int imageID;

            private void Page_Load(object sender, System.EventArgs e)
            {
                  if (!IsPostBack) imageID = 5;
            }
      }
}

how can I get the imageID property to keep it's value on a postback?

bd
Avatar of softplus
softplus

Try a bit of Viewstate: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnaspnet/html/asp11222001.asp
:)
or add a hidden literal/label/field to the page
softplus is correct; throw that variable in the ViewState bag and grab it in your postback.  Something kind of like this:

private void Page_Load(object sender, System.EventArgs e)
{
   if(!this.IsPostBack || ViewState["imageID"] == null)
   {
      this.imageID = 5;
      ViewState["imageID"] = this.imageID;
   }
   else
      this.imageID = (int)ViewState["imageID"];
}
Avatar of brooklynDev

ASKER

so I take it that dev I was talking about was wrong, and page variables as illustrated in my question can and do not persist across postbacks
ASKER CERTIFIED SOLUTION
Avatar of BurntSky
BurntSky

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial