...

View Full Version : ASP.NET List<object> help



us3rnam3
05-31-2012, 10:50 PM
Hi there.

I'm trying to implement some kind of basic shopping cart but I've run into an issue I'm not able to solve.

I've got an Add() method, which is obviously supposed to add items to the cart. That part is working like it should. The problem is when I add an item that already exists in the list, I wanted it to update the quantity for the item instead of adding a new pair (itemID - itemQuantity) to the DataTable.

Here's the code I have:



//Add items to the cart
public void Add(int ItemID, int Qty)
{
//verify if item already exists in the cart
int k = ItemExists(ItemID);
//if it exists
if (k != -1)
Items[k].Quantity += Qty; //increment quantity for the item (this is the part that's not working)
else
{
ClsCartItem item = new ClsCartItem(ItemID,Qty); //creates new item
this.Items.Add(item); //adds it to the list
}




//verify if item already exists in the cart
public int ItemExists(int ID)
{
foreach (ClsCartItem item in this.Items)
{
if (item.ItemID == ID)
{
return Items.IndexOf(item); //return the index of the item in the list
}
}
return -1; //there's no match for the item ID in the list


When an user clicks the "add to cart" button I'm calling the method with the ID of the item passed by QueryString and a quantity of 1 (for testing porpouses) like this:



(...)
if ((Request.QueryString["User"] != null) && (Request.QueryString["ItemID"] != null))
{

if (Session["Cart"] != null) //if there's a Session already
{
c = (ClsCart)Session["Cart"]; //retrieves the items from the Session object
}
else
{
c = new ClsCart(); //creates new cart
}
c.Add(Convert.ToInt32(Request.QueryString["ItemID"]), 1);
Session["Cart"] = c;


Any ideas on why the part in red is not working properly?

Obs: Items is a List of ClsCartItem objects

Thanks in advance :D

us3rnam3
06-04-2012, 01:23 PM
It seems like the problem is solved.
The problem was I wasn't updating the value of the properties correctly in the set { name = value; } option of the ClsCartItem class.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum