Aan
Aan

Reputation: 12890

When do I need to use ViewState

I am confused in how to use ViewState in C#, for example what is the benefit of using:

ViewState["VST"]="Value1";

Lable1.Text= ViewState["VST"].ToString();

Whereas I can use:

string container= "Value1";
Lable1.Text= container;

Upvotes: 2

Views: 3658

Answers (4)

masterlopau
masterlopau

Reputation: 563

Every time your application do postbacks current values of your controls are being wiped out. So in order for you to store any values WITHIN THE PAGE you can save them in ViewState. Of course you must set the EnableViewState property first to true. Additional info, if you want to store any value or state while jumping into multiple pages you can use Session instead.

Upvotes: 1

4b0
4b0

Reputation: 22323

As per documentation:

View state is used automatically by the ASP.NET page framework to persist information that must be preserved between postbacks. This information includes any non-default values of controls. You can also use view state to store application data that is specific to a page.

For details see a link:http://msdn.microsoft.com/en-us/library/bb386448(v=vs.100).aspx

Upvotes: 2

Rohit Vyas
Rohit Vyas

Reputation: 1969

If you want to persist the values after postback also than ViewState is the best option.

Upvotes: 1

ericosg
ericosg

Reputation: 4965

Your ViewState consists of variables that are kept with the post-backs of your page, because they are sent to the client and the client sends them back with the entire page.

Hence, if you do:

string container= "Value1";
Lable1.Text= container;

Then the users sees the page and hits the submit button, your container string will not exist.

If however you uses the ViewState, ViewState["VST"] will still have the value as it will be "refreshed" when the user submits and sends the page back.

Read more here and also understand the ASP.NET page life cycle.

Upvotes: 4

Related Questions