Last post Jun 09, 2008 03:43 AM by dhassen
Jun 06, 2008 06:50 AM|dhassen|LINK
I've created a ShoppingCart class that is a list of another class - cartItems. I want to be able to remove a cart item and I'm struggling a little with how to go about it correctly.
I've tried the following:
For Each item As CartItem In Profile.ShoppingCart.Items
If item.ItemID = 11 Then
But get this error: Collection was modified; enumeration operation may not execute.
Is there a way round this. I want the user to be able to delete an item from their shopping cart. (the shopping cart is stored as profile info)
Thanks in advance
Jun 06, 2008 11:43 AM|Garbin|LINK
you can't remove an item from a collection you're iterating with foreach. Beside that, removing an item from a collection you're iterating is dangerous, because if you don't write carefully the loop (for example, iterating backwards) you risk to get out
My suggestion is: use a classic for loop. As soon as you find the item to remove, save the index to a variable and break from the loop. Then, pass the index to the RemoveAt method of the collection.
Jun 09, 2008 03:43 AM|dhassen|LINK
Thanks for your suggested solution. I actually resolved this not long after I posted, but forgot to reply to myself. I checked whether I wanted to delete within the for loop, but didn't try and remove the item within the loop. Here's the code I used:
Dim item2 As CartItem
For Each item1 As CartItem In Profile.ShoppingCart.Items
Dim TheID = item1.ItemID
If item1.ItemID = ItemID Then
item2 = item1
If item2 IsNot Nothing Then