Subscribe

RSS Feed (xml)

Creating Stateful Page Member Variables

ASP.NET provides several state mechanisms, as described in previous post. However, none of these can be used automatically-they 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.)
}



Technorati :

No comments:

Variety in the Web World