Click to See Complete Forum and Search --> : Increment Problem


Clapy2202
April 20th, 2003, 07:48 AM
I have tried to increase an int variable when I press a button. The problem is that it works only the first time. After that, when I press the button it does the same thing over and over again.

For example:

public class WebForm1 : System.Web.UI.Page

...........

public int n;

............

private void Button1_Click(object sender, System.EventArgs e)
{
nr++
LabelTest.Text = nr.ToString();
}

I have tried the exactly same thing on a windows form and it' working just fine. Can anyone tell me how I can remember an incremented value?

I think it could be done if I would use a DataBase (SQL or something), but I would like to avoid using one.

aftermoon
April 21st, 2003, 01:56 AM
if ur aim is just to display the incrimented value in a label, why don't u use label1.text = val(label1.text) + 1. :D

If it's not the case, try cookies or hidden variable rather than database.

aftermoon
April 23rd, 2003, 01:49 AM
Hey, better you declare a public variable in a module.
so it can be easily incrimented.

V. Lorenzo
April 28th, 2003, 02:59 AM
Hi:

There is no problem with the variable 'inc' operation. It is a desired behaviour.

Each time the page is served (due to the first request or due to any response to a client postback), the entire page is recreated from scratch.

If you want a variable value to be persistent from one trip to the server to another, you're responsible for that. So, how can you make it persistent? Well, there are several ways but the most used are :

1- Mark the variable class with the [Serializable] attribute and store it's value in the control's (or Page) ViewState.
2- Store the variable in the Session items collection.
3- Store the variable in the Application items collection.

You'll find several samples in the online VStudio documentation, and lots of samples in dedicated sites.

Bye