Be aware that if you set a variable before postback and then check it after postback it will be reset, use Session or ViewState to keep variable values regardless of postback state.

ViewState is a collection bag which holds key value pairs of changed control attributes. You can also utilize it to store your own values which will persist though a Page’s postbacks. ViewState is a member of Page, which means it is globably accessible throughout your Page. The ViewState is loaded early on in the Page creation (life cycle), and towards the end it is encrypted and outputed into the HTML. Therefore, when you add some data to the ViewState on the first page load, that data is being stored (encrypted) in the __ViewState hidden field you’ll find in the HTML source.  When the page is loaded again (after you click the button), that value is decrypted and loaded into the ViewState bag, which means you’ll be able to access it.

Remember to always check if the value you are getting (either from ViewState or Session) is null or not. If not, you’re users will get the infamous “Object reference not sent to an instance of an object.” exception.

ViewState is the mechanism that allows state values to be preserved across page postbacks.

Because of the stateless nature of web pages, regular page member variables will not maintain their values across postbacks.  When we need a page variable to maintain its value across page post backs, we can use ViewState to store that value.  Values stored in ViewState will be serialized and sent to the client browser as the value of a hidden form input.  When you view the page source (in your browser) of a page the uses ViewState, you may see this hidden viewstate input which will look something like this:

<input type=”hidden” name=”__VIEWSTATE” id=”__VIEWSTATE” value=”/wQPDwAKMTn1ODM5Rj…….” />

This single hidden field contains all the viewstate values for all the page controls. This is an important aspect of viewstate that you need to consider.

Example

One simple way to store small values in viewstate is to use a property instead of a member variable.  This property can use viewstate to store its value rather than a member variable that would lose the value over a postback. For example, storing an Integer in viewstate can be accomplished like this:

VB

Public Property SomeInteger() As Integer

Get

Dim o As Object = ViewState(“SomeInteger”)

If Not o Is Nothing Then Return DirectCast(o, Integer)

Return 0 ‘a default

End Get

Set(ByVal value As Integer)

ViewState(“SomeInteger”) = value

End Set

End Property