Persist Data Across Postbacks With View State

View state isn’t just for control development anymore. Use this technique to save data between postbacks.

Jeff Prosise

October 30, 2009

2 Min Read
ITPro Today logo in a gray background | ITPro Today

Hot Tip

LANGUAGE: C#

ASP.NET VERSIONS:1.0 | 1.1

 

Persist Data Across Postbacks With View State

View state isn't just for control development anymore.Use this technique to save data between postbacks.

 

By Jeff Prosise

 

Many ASP.NET programmers associate view state with controldevelopment. But page developers can use view state, too, to persist dataacross postbacks. To demonstrate, here's a page that hosts a DataGrid thatsupports paging and sorting. The sorting routine writes data into view statethat lets the paging logic remember how the DataGrid was last sorted - anessential feature if sorts are to be retained when the DataGrid is paged:

 

<%@ Import Namespace="System.Data" %>

<%@ Import Namespace="System.Data.SqlClient" %>

 

  

    

               AutoGenerateColumns="false" CellPadding="2"         Font-Name="Verdana" Font-Size="8pt"         AllowPaging="true" PageSize="16"         OnPageIndexChanged="OnPage" Width="100%"          AllowSorting="true"OnSortCommand="OnSort">                                 DataField="productid"             ItemStyle-HorizontalAlign="center" />                         DataField="productname"             SortExpression="productname ASC" />                        DataField="unitsinstock"             SortExpression="unitsinstock ASC" />                             Font-Bold="true" HorizontalAlign="center" />                     

  

 

void Page_Load (Object sender, EventArgs e) {    if (!IsPostBack) {        SqlDataAdapteradapter = new SqlDataAdapter (           "selectproductid, productname, unitsinstock " +           "fromproducts",            "server=localhost;database=northwind;uid=sa"         );          DataSet ds = newDataSet ();        adapter.Fill (ds);         MyDataGrid.DataSource = ds;         MyDataGrid.DataBind ();    }}  void OnPage (Object sender,     DataGridPageChangedEventArgs e) {    MyDataGrid.CurrentPageIndex = e.NewPageIndex;       SqlDataAdapter adapter= new SqlDataAdapter (       "selectproductid, productname, unitsinstock " +       "fromproducts",        "server=localhost;database=northwind;uid=sa"     );      // Apply the last sort(if any)     object obj = ViewState["SortExpression"];     if (obj != null) {        string exp =(string) obj;         adapter.SelectCommand.CommandText +=            " orderby " + exp;     }      DataSet ds = newDataSet ();    adapter.Fill (ds);     MyDataGrid.DataSource= ds;      MyDataGrid.DataBind ();}  void OnSort (Object sender,     DataGridSortCommandEventArgs e) {    SqlDataAdapter adapter= new SqlDataAdapter (       "selectproductid, productname, unitsinstock " +       "from productsorder by " +       e.SortExpression.ToString(),       "server=localhost;database=northwind;uid=sa"     );      DataSet ds = newDataSet ();    adapter.Fill (ds);     MyDataGrid.DataSource= ds;     MyDataGrid.DataBind();      // Remember how thegrid was last sorted    ViewState["SortExpression"]=        e.SortExpression.ToString ();}

 

Jeff Prosise isauthor of several books, including Programming Microsoft .NET (MicrosoftPress). He also is a co-founder of Wintellect (http://www.wintellect.com), asoftware consulting and education firm that specializes in .NET. Contact Jeffat [email protected].

 

 

 

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like