• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 319
  • Last Modified:

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
0
SuperMario
Asked:
SuperMario
  • 2
  • 2
1 Solution
 
HummusxCommented:
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.
0
 
HummusxCommented:
Erg sorry I posted it in VB.  I keep doing that.  It should be close enough for you to move into C#.  If not, let me know and I can translate it.
0
 
SuperMarioAuthor Commented:
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...
0
 
SuperMarioAuthor Commented:
That did the trick! Thank you Hummusx. Your help's much appreciated.

-Dan
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now