65.9K
CodeProject is changing. Read more.
Home

Preserving State

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.36/5 (5 votes)

Aug 18, 2005

viewsIcon

27037

downloadIcon

171

How to easily preserve the state of any object with only a few lines of code.

Introduction

One of the biggest problems in ASP.NET in my opinion is preserving state. So I decided to create a way to preserve state in a HashTable that required very little code. Basically, I overrode a few events and had the application save and load the hash whenever the page is rendered or loaded. This is no big trick, but saves me a lot of time and I use it pretty much everywhere.

Declaring the Hash

Add a simple declaration to the top of your program:

     Public StateHash As New Hashtable

Overrides

All we need to do now is Override the OnLoad and OnPreRender events for the page, load our hash and then continue running the respective event.

    Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
        If Not (viewstate("__StateHash") Is Nothing) Then
            StateHash = viewstate("__StateHash")
        End If

        MyBase.OnLoad(e)
    End Sub

    Protected Overrides Sub OnPreRender(ByVal e As System.EventArgs)
        viewstate("__StateHash") = StateHash

        MyBase.OnPreRender(e)
    End Sub

Now anything you assign to StateHash will be automatically preserved.

Example Assignments

    StateHash("Name")="Matthew"
    StateHash("ID")=12234
    StateHash("url")="http://codeproject.com/"

Please see the download for more examples.