Link to home
Start Free TrialLog in
Avatar of SuperMario
SuperMario

asked on

Persistent ArrayLists between pageviews in ASP.NET

Hey all,
I've got an ArrayList in my ASP.NET page. Basically, I want the user to be able to add items into an arraylist by pressing a button. However, each time they do this the page reloads and their array is initialized to nothing.

1) Where should I put my line: array = new ArrayList(0); in order to avoid re-initialization
2) How do I make the arraylist persist after the button is clicked?

Thanks,
-Dan
Avatar of Hummusx
Hummusx

Well, what you want to do is wrap your initialization in an if statement like this:


If Not IsPostBack() Then
  'Initialize
Else
  'Restore from wherever you stash it
End If

You can either put it in Viewstate or in Session.  It depends how large it will be and how much of a load you will have on your server.  If you aren't worried about server load, just stick it in the session state when you are done with it on the page:

Session("myArrayList") = myArrayList

Then in the "else" portion do something like this:

myArrayList = CType(Session("myArrayList"), ArrayList)


So basically if the user is just coming to the page, it will run the initialization and create the object.  Otherwise, it will reinstate the one saved in the session.  If you want to keep it between pages, you can change your if statement to:

If Session("myArrayList") Is Nothing Then
  'Initialize
Else
  myArrayList = CType(Session("myArrayList"), ArrayList)
End If

So in this case it will always check to see if it exists in the session.  If not, it will create it.
ASKER CERTIFIED SOLUTION
Avatar of Hummusx
Hummusx

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of SuperMario

ASKER

I'll give this a try, it sounds like it will work. And don't worry about the VB. I wrote a lot of classic ASP 3.0 over the past couple of years ;) I miss the ADODB.Recordset object...
That did the trick! Thank you Hummusx. Your help's much appreciated.

-Dan