Click here to Skip to main content
15,892,298 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In my asp.net application I declare global variable and datatype is int. But when a postback happened it can not store the previous value. It becomes zero. I need to keep these values to use later. Is it possible. Please help me.
Posted
Comments
Mukesh Pr@sad 21-Nov-14 7:35am    
u can use viewstate object or make that variable as static.

1.The web application is different then the desktop application. On each postback the entire application's objects that manage the UI events are recreated, so also the static variable.

2.In order the preserve the value between postbacks you have to cache their values. If is a global object that does not depends on the current web user (is at application level) you should cache it in Application cache, if the object depends only on each web user session, you should cache it on Session cache.

3.For details about saving the data state between postbacks and/or pages see the next link: http://msdn.microsoft.com/en-us/library/75x4ha6s(v=vs.100).aspx[^]
 
Share this answer
 
v2
try..

C#
public static int i = 0;
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
    i++;
    lblMsg.Text = "Clicked"+i.ToString();
}

if you want to reset the value in page load then use..

C#
protected void Page_Load(object sender, EventArgs e)
{
 if (!IsPostBack)
 {
  i = 0;
 }

}
 
Share this answer
 
v3
Use the IsPostBack [^]property to add a check on your Page_Load method.

C#
int i = 0;

private void Page_Load()
{
    if (!IsPostBack)
    {
       //only initialise if not a post back
       i = 100;
    }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900