Preserving the value of an int between postbacks

G

Guest

I am developing an ASP.NET app in C#. I am attempting to use an int as a
counter which will be incremented each time a user submits a webform adding
data to a list. Initially I tried to use a session variable, but had some
issues converting that value to an int. So I've tried using an int which is
declared as a class variable. However when I post back the page the int gets
reset back to zero. Is there a way to preserve the value?
 
D

David Young

Mike,
Since HTTP is a stateless protocol, you have to find a way to persist the
value between posts. There are several methods to do this.
1) Use hidden fields: You could use a hidden field to hold the value of the
int you are wanting to increment.
Example: int myInt = Convert.ToInt32(myhiddenfield.Text); Then you can
increment as needed.

2) Use the session object: You can save any object to session.
Example:
Session["myInt"] = 1;
int myInt = Convert.ToInt32(Session["myInt"]);

There are other means as well, but those two are the most common.
 
W

WJ

I would use Html Hidden field instead. On Page_load, do this:

//*********************
if(!IsPostBack)
{
htmlHiddenField.Value="0";
}

int hitCount=Convert.ToInt32(htmlHiddenField.Value); //current count
hitCount++; //Bump pass 1
htmlHiddenField.Value=hitCount.ToString(); //preserve it for next trip
//***********

John
 
G

Guest

Thanks for both suggestions it worked.

WJ said:
I would use Html Hidden field instead. On Page_load, do this:

//*********************
if(!IsPostBack)
{
htmlHiddenField.Value="0";
}

int hitCount=Convert.ToInt32(htmlHiddenField.Value); //current count
hitCount++; //Bump pass 1
htmlHiddenField.Value=hitCount.ToString(); //preserve it for next trip
//***********

John
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,898
Latest member
BlairH7607

Latest Threads

Top