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 PreservedMembers1
Inherits System.Web.UI.PageDim firstName, lastName As String
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Me.IsPostBack Then
‘Restore variables
firstName = CStr(ViewState(“FirstName”))
lastName = CStr(ViewState(“LastName”))
End If
End Sub
Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
‘Keep variables
ViewState(“FirstName”) = firstName
ViewState(“LastName”) = lastName
End SubProtected Sub cmdSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles cmdSave.Click
firstName = txtFirstName.Text
txtFirstName.Text = “”lastName = txtLastName.Text
txtLastName.Text = “”
End SubProtected Sub cmdLoad_Click(ByVal sender As Object, ByVal e As EventArgs) Handles cmdLoad.Click
txtFirstName.Text = firstName
txtLastName.Text = lastName
End SubEnd Class