How to create Add to Cart

4k Views Asked by At

I want to make a simple online store that can buy multiple items. Here is my code

public void BuyItem(int deviceid, int quantity)
    {
        Dictionary<int, int> devicelist = new Dictionary<int, int>();
        devicelist.Add(deviceid, quantity);

        Device devices = (from device in master.Devices
                      where device.IDDevice == deviceid
                      select device).SingleOrDefault();
        customer = os.GetCustomer(User);
        //List<CartShop> cartList = new List<CartShop>();
        //var toCart = devices.ToList();
        //foreach (var dataCart in toCart)
        //{
            cartList.Add(new CartShop
            {
                IDDevice = deviceid,
                IDLocation = devices.IDLocation,
                IDCustomer = customer,
                Name = devices.Name,
                Quantity = quantity,
                Price = Convert.ToInt32(devices.Price) * quantity
            });
            cartTotal = cartList;
            StoreTransaksi.DataSource = new BindingList<CartShop>(cartTotal);
            StoreTransaksi.DataBind();
        //}
        X.Msg.Show(new MessageBoxConfig
        {
            Buttons = MessageBox.Button.OK,
            Icon = MessageBox.Icon.INFO,
            Title = "INFO",
            Message = "Success"
        });
    }

But it only can add 1 item, after choose the other item, it replace the old one. (Could not add more than one). Please help

1

There are 1 best solutions below

3
On BEST ANSWER

The issue is that cartTotal is the same as cartList (take a look at this). You need to do the following for copying a list to another without keeping the reference:

cartTotal = new list<cartShop>(cartList);

Also note that this is still in the method and will be created each time you call the method.

Update: This is a very simple console application that does what you need:

internal class Program
{
    public static List<Item> ShoppingCart { get; set; }

    public static void Main()
    {
        ShoppingCart = new List<Item>();
        AddToCart(new Item() { ProductId = 2322, Quantity = 1 });
        AddToCart(new Item() { ProductId = 5423, Quantity = 2 });
        AddToCart(new Item() { ProductId = 1538, Quantity = 1 });
        AddToCart(new Item() { ProductId = 8522, Quantity = 1 });
    }

    public static void AddToCart(Item item)
    {
        ShoppingCart.Add(new Item() { ProductId = item.ProductId, Quantity = item.Quantity});
    }
}

public class Item
{
    public int ProductId { get; set; }
    public int Quantity { get; set; }
}