Click here to Skip to main content
Click here to Skip to main content

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.

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.

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

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.
 


Comments and Discussions

 
QuestionWhy? Pinmembermwdiablo20-Aug-05 19:51 
GeneralWhy not use the Session Pinmembermagister19-Aug-05 0:40 
QuestionWhy use a Hashtable for this when ViewState implements IDictionary? PinmemberDavid Kemp18-Aug-05 22:26 

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

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

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