Question

What would be the best way to create a dynamic array for a user to add products to a basket then store them in a session variable, I have been told serilizable arrays would work however when looking online for a solution I came accross an ArrayList which seemed perfect but I can't seem to implement it.

I have a separate class called Basket with:

ArrayList basketItems = new ArrayList();

I need to be able to select a product from a gridview using the select link or alternatively using a listview and using my own button to then add the bookID to the array, which will then be stored in a session variable and sent to a basket page where the bookID will be used again against a SQL table to output the details of the book etc.

Was it helpful?

Solution

If we were in 2003 then yes, ArrayList could have worked fine but now I would recommend you using a generic List<T> which will be type safe and you don't need casting.

So you could have the following collection:

List<int> productIds = new List<int>();
productIds.Add(1);
productIds.Add(2);

OTHER TIPS

The ArrayList is the usual .NET 1.x solution for this problem. If you are using .NET 2.0 or later, use a simple generic list (List<T>).

Like this:

var myIDs = new List<int>();

You can add items with the Add method.

myIDs.Add(2);
myIDs.Add(42);

You can assign it to a session variable this way:

Session["IdList"] = myIDs;

And you can recover it:

var stuff = (List<int>)Session["IdList"];

Hope this helps

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top