Mtok
Mtok

Reputation: 1630

What type of variables should I use?

I am developing an asp.net web site. I have an aspx page. I want to use a variable whose value shouldn't be resetted during a postback, but when pass to another page and turn back it should be resetted. And also I'am changing this variables value in the code behind in C#. So it should change when I want, it shouldnt be resetted during a postback and it should be resetted when I navigate to another page.

I tried to use

public int
public static int
protected int

but I couldnt realize which one is working right.

Upvotes: 1

Views: 99

Answers (2)

Magnus Johansson
Magnus Johansson

Reputation: 28325

The ability to preserve data over post backs isn't really up to the variable scope. It really doesn't matter if you choose public, protected or private.

The technique you are looking for is either called Session State or View State.
Session state preserves data across different pages and view state within the same page. There is actually also a 3rd, the Application state object which preserves data globally across different user sessions as well.

In the most simple form, you would user a view state like:

string myString = "123";
ViewState["MyString"] = myString;

and after the post back , in the Page_Load method:

myString = ViewState["MyString"].ToString();

Upvotes: 4

rene
rene

Reputation: 42414

Look into

Session["yourvar"] = 123; 

and

Application["globalvar"] = 456;

msdn documentation here

Upvotes: 1

Related Questions