Click here to Skip to main content
15,884,472 members
Articles / Web Development / ASP.NET
Article

Preserving State

Rate me:
Please Sign up or sign in to vote.
2.36/5 (5 votes)
18 Aug 2005 26.7K   14   3
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:

VB
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.

VB
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

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

Please see the download for more examples.

License

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


Written By
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.



Comments and Discussions

 
QuestionWhy? Pin
KiwiPiet20-Aug-05 19:51
KiwiPiet20-Aug-05 19:51 
GeneralWhy not use the Session Pin
magister19-Aug-05 0:40
magister19-Aug-05 0:40 
QuestionWhy use a Hashtable for this when ViewState implements IDictionary? Pin
David Kemp18-Aug-05 22:26
David 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.