How to preserve member variables for an ASP.NET page in C#

Software developers can follow the next basic principle. They can save all member variables to View state when the Page.PreRender event occurs and retrieve them when the Page.Load event occurs. The Page.Load event happens every time the page is created. In case of a postback, the Load event occurs first, followed by any other control events. The next example illustrates the principle:

public class PreserveMembers: Page
{
        // Member variables that will be cleared with every postback
        private string fistName, lastName;
        protected void Page_Load(Object sender, EventArgs e)
        {
          if ( this.IsPostBack )
          {
          // Restore variables
            firstName = (string)ViewState[“FirstName”];
            lastName  = (string)ViewState[“LastName”];
          }
        }
        protected void Page_PreRender(Object sender, EventArgs e)
        {
          // Keep variables
          ViewState[“FirstName”] = firstName;
          ViewState[“LastName”]  = lastName;
        }
        protected void cmdSave_Click(Object sender, EventArgs e)
        {
          // Transfer contents of the text boxes to member variables
          firstName = txtFisrtName.Text;
          txtFisrtName.Text = “”;

          lastName = txtLastName.Text;
          txtLastName.Text = “”;
        }
        protected void cmdLoad_Click(Object sender, EventArgs e)
        {
          // Restore contents of the member variables to text boxes
          txtFisrtName.Text = firstName;
          txtLastName.Text = lastName;
        }
}