This documentation is archived and is not being maintained.

Code: Reading a Value From View State (Visual C#)

Visual Studio .NET 2003

This example saves the value "yellow" to the Control.ViewState property and then, when the page posts back to the server, retrieves a value of the property. For more information on ViewState, see Saving Web Forms Page Values Using View State.

Example

string strColor;
if (Page.IsPostBack)
{
   // Retrieve and display the property value.
   strColor = (string)ViewState["color"];
   Response.Write(strColor);
}
else
   // Save the property value.
   ViewState["color"] = "yellow";

Compiling the Code

Copy and paste the code into the Page_Load method of an ASP.NET Web application.

Robust Programming

As shown in the example, retrieving the ViewState property occurs when the Web page is posted back to the server. Otherwise, the string will be null.

For more information on usage recommendations, see State Management Recommendations.

See Also

Code: Saving a Value in View State (Visual C#) | State Management Recommendations | Developing High-Performance ASP.NET Applications | Web Applications Example Topics

Show: