Each control on a Web Forms page, including the page itself, has a ViewState property that it inherits from the base Control class. View state is used by the ASP.NET page framework to automatically save the values of the page and of each control just prior to rendering to the page. When the page is posted, one of the first tasks performed by page processing is to restore view state.
You can use the ViewState property to save your values independent of control state between round trips to the server. The ViewState property is stored in the page in a hidden form field.
Note In order to use the
ViewState property, your form must have a server form element (
<form runat="server">
). For usage recommendations, see
State Management Recommendations.
To store information in view state
- Create and store a new element in the ViewState property.
Note The data must be in a format compatible with view state. For example, to store a dataset in view state, you should first convert it to a string representation.
' Visual Basic
ViewState("color") = "yellow"
// C#
ViewState["color"] = "red";
To retrieve information from view state
The following example shows you can save a dataset in view state and then retrieve it. To save it, you create a string representation of it using the dataset's DataSet.WriteXml method. When retrieving the dataset, you cast it to a StringReader class and then call the dataset's DataSet.ReadXml method.
' Visual Basic
If Page.IsPostBack Then
Dim sr as New System.IO.StringReader(CStr(ViewState("dsCustomers")))
DsCustomers1.ReadXml(sr)
Else
SqlDataAdapter1.Fill(DsCustomers1)
Dim sw as New System.IO.StringWriter()
DsCustomers1.WriteXml(sw)
ViewState("dsCustomers") = sw.ToString()
End If
// C#
if (Page.IsPostBack)
{
System.IO.StringReader sr = new System.IO.StringReader((string)(ViewState["dsCustomers"]));
dsCustomers1.ReadXml(sr);
}
else
{
sqlDataAdapter1.Fill(dsCustomers1);
System.IO.StringWriter sw = new System.IO.StringWriter();
dsCustomers1.WriteXml(sw);
ViewState["dsCustomers"] = sw.ToString();
}
See Also
Web Forms State Management | Introduction to Web Forms State Management | Maintaining State in a Control | Programming Web Forms | State Management Recommendations | Developing High-Performance ASP.NET Applications