Search Web

Thursday, August 19, 2010

How to Store Values In View State..??

ASP.NET has a built in mechanism for storing values of controls known as ViewState.
The ViewState property provides a key-value object for storing values between multiple requests of the same page.
ASP.NET saves the state of the page and controls as a hashed string in the page as a hidden variable, ViewState.
When a page is run, the ViewState property can be seen from the source code of the page.

<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" 
value="/wEWAgL3ku32BwLs0bLrBqcPjj4o1kvxlT2D91sy/YSkJDTh" />

Custom data can be stored in the ViewState property.

If a value has to be stored for a user in page, ViewState is an easy way to achieve this.
Please note that ViewState property is only accessible from the page only.
If the user visits a different page, the ViewState property will be lost.

Let's create a string containing a date and store it in the ViewState.

string date = DateTime.Now.ToString();

ViewState["date"] = date;

An alternative way of achieving this would be to

ViewState.Add("date", date);

The values stored in the ViewState can also be retrieved as follows.

if ((string)ViewState["date"] != null)


string date2 = (string)ViewState["date"];


Here, I am checking there a ViewState property named "date". If so, assign the value to string date2.
In ViewState, objects can also be stored/ For example, we can store a DateTime object like below

ViewState.Add("date3", DateTime.Now);

and retrieve the object like

DateTime date3 = (DateTime)ViewState["date3"];

That's It....!!


Post a Comment