如何创建添加到购物车

时间:2016-12-28 08:02:56

标签: c# shopping-cart

我想制作一个可以购买多件商品的简单在线商店。 这是我的代码

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"
        });
    }

但它只能添加1个项目,在选择其他项目后,它会替换旧项目。 (无法添加多个)。 请帮忙

1 个答案:

答案 0 :(得分:1)

问题是cartTotal与cartList相同(请查看this)。您需要执行以下操作才能将列表复制到另一个列表而不保留引用:

cartTotal = new list<cartShop>(cartList);

另请注意,这仍然在方法中,并且每次调用方法时都会创建。

更新: 这是一个非常简单的控制台应用程序,可以满足您的需求:

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; }
}