Name

ViewState

Synopsis

StateBag = Page.ViewState

The ViewState property returns an instance of the StateBag class containing state information for server controls on the page. This StateBag instance can also be used to store arbitrary data that needs to be preserved across multiple requests for the same page.

Parameters

StateBag

An object of type StateBag that contains the property values for server controls on the page. This StateBag instance can also be used to store arbitrary data that needs to be preserved across multiple requests for the same page.

Example

The following code example sets the ForeColor property of the Message control, and then stores the value of that color in the ViewState StateBag instance. If the page is posted back, the code retrieves the color that was stored, and depending on the name of the color, changes the color from Red to Black, or vice-versa.

<%@ Page Language="vb" %> <html> <head> <title>ViewState property example</title> <script runat="server"> Sub Page_Load( ) Dim LocalColor As System.Drawing.Color If IsPostBack Then LocalColor = CType(ViewState("LabelColor"), _ System.Drawing.Color) If LocalColor.Name = "Black" Then LocalColor = System.Drawing.Color.Red Else LocalColor = System.Drawing.Color.Black End If Message.ForeColor = LocalColor Message.Text = "Label color is " & LocalColor.Name ViewState("LabelColor") = LocalColor Else Message.ForeColor = System.Drawing.Color.Black LocalColor = Message.ForeColor Message.Text = "Label color is " & LocalColor.Name ...

Get ASP.NET in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.