7.3 Create Stateful Page Member Variables


7.3 Create Stateful Page Member Variables

Problem

You need to create member variables in your page class and ensure that their values are retained when the page is posted back.

Solution

Respond to the Page.PreRender event, and write all the member variables into view state. Respond to the Page.Load event, and get all the values of the member variables from view state. The rest of your code can now interact with these variables without worrying about state issues.

Discussion

ASP.NET provides several state mechanisms, as described in recipe 7.2. However, none of these can be used automaticallythey all require manual code to serialize and retrieve information. You can add a layer of abstraction by performing this serialization and retrieval once. The rest of your code can then interact directly with the member variables.

In order for this approach to work, you need to read variable values at the start of every postback. The Page.Load event is an ideal choice for this code because it always fires before any other control events. You can use a Page.Load event handler to pre-initialize all your variables. In addition, you need to store all variables before the page is sent to the user , after all processing is complete. In this case, you can respond to the Page.PreRender event, which fires after all event handlers, just before the page is converted to HTML and sent to the client.

The following page shows an example of how you might persist one Page member variable (named memberValue ).

 using System; using System.Web; using System.Web.UI.WebControls; public class StatefulMembers : System.Web.UI.Page {     // (Designer code omitted.)     private int memberValue = 0;     private void Page_Load(object sender, System.EventArgs e) {         // Reload all member variables.         if (ViewState["memberValue"] != null) {             memberValue = (int)ViewState["memberValue"];         }     }     private void StatefulMembers_PreRender(object sender,        System.EventArgs e) {         // Save all member variables.         ViewState["memberValue"] = memberValue;         // Display value.         lblCurrent.Text = memberValue.ToString();     }     // (Other event handlers can now work with memberValue directly.) } 



C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net