7.9. Managing State: Class Members

How do we store the mouse click count? My first thought was to introduce instance members within the WebForm1 class that represents the page:

public class WebForm1 : System.Web.UI.Page
{
   // generated by Web Forms designer ...
   protected System.Web.UI.WebControls.TextBox TextBox1;
   protected System.Web.UI.WebControls.Label Label1;
   protected System.Web.UI.WebControls.Label Label2;
   protected System.Web.UI.WebControls.ListBox ListBox1;
   protected System.Web.UI.WebControls.Label Label3;
   protected System.Web.UI.WebControls.ImageButton ImageButton1;

   // OK: my guys ...
   protected int AnnaCount;
   protected int PoohCount;
   protected int MissCount;

Unfortunately, this fails miserably. The page is reloaded with each post back, and each instance member is initialized to its default value. The control view state is then restored before the Load event is invoked. This means that with each post back, class instance variables are always initialized back to 0. If an instance is set to 1 within the on-click event handler, that value is lost.

Turning the three instance members into static members appears to work correctly, but only for a session of a single page. The value associated with each static member of the page persists across posts back, and therefore reflects the running hit count. Unfortunately, the value also persists across sessions running either concurrently or following one another. This is why the Pooh count in Figure 7.4 is too large. It reflects the mouse clicks of the current session and a previous session.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.70.247