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
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:
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: