Click here to Skip to main content
13,193,650 members (57,136 online)
Click here to Skip to main content
Add your own
alternative version


14 bookmarked
Posted 18 Aug 2005

Preserving State

, 18 Aug 2005
Rate this:
Please Sign up or sign in to vote.
How to easily preserve the state of any object with only a few lines of code.


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


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

End Sub

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

End Sub

Now anything you assign to StateHash will be automatically preserved.

Example Assignments


Please see the download for more examples.


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Matthew Hazlett
Web Developer
United States United States
I started programming for fun when I was about 10 on an Franklin Ace 1000.

I still do it just for fun but it has gotten me a few jobs over the years. More then I can say for my Microsoft Certifications. Smile | :)

The way I learned was by example, now its time to give back to the next generation of coders.

You may also be interested in...

Comments and Discussions

QuestionWhy? Pin
mwdiablo20-Aug-05 19:51
membermwdiablo20-Aug-05 19:51 
GeneralWhy not use the Session Pin
magister19-Aug-05 0:40
membermagister19-Aug-05 0:40 
QuestionWhy use a Hashtable for this when ViewState implements IDictionary? Pin
David Kemp18-Aug-05 22:26
memberDavid Kemp18-Aug-05 22:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.171018.2 | Last Updated 18 Aug 2005
Article Copyright 2005 by Matthew Hazlett
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid