我的问题如下:我有两个ListBoxe
s. 第一个是我存储产品,可以订购,第二个是客户的购物车。所以一个产品有一个 Quantity 属性,我有一个NumericUpDown
,客户可以在其中更改订购产品的数量。
private void button2_Click(object sender, EventArgs e) //puts selectedproduct to the cart
{
if (listBox1.SelectedItem == null || (int)numericUpDown1.Value == 0 ||
(listBox1.SelectedItem as Product).Quantity < (int)numericUpDown1.Value) return;
foreach (Product item in listBox2.Items)
{
if (item.ID == (listBox1.SelectedItem as Product).ID)
{
return;
}
}
listBox2.Items.Add(new Product { Name = (listBox1.SelectedItem as Product).Name,
Price = (listBox1.SelectedItem as Product).Price,
Quantity = (int)numericUpDown1.Value});
(listBox1.SelectedItem as Product).Quantity -= (int)numericUpDown1.Value;
}
这很好用,除了它在我的 Products 表中添加了一个新项目。我想要做的事情是向客户购物车添加所选数量的所选产品,而不是向产品表中添加新项目,并使用 numericupdown1.value 减少订购的产品数量。我正在使用 EF Code First 数据库,看起来像:
public class Order
{
public int ID { get; set; }
public bool Status { get; set; }
public virtual Account account { get; set; }
public virtual List<Product> products { get; set; }
}
public class Product
{
public int ID { get; set; }
public string Name { get; set; }
public long Price { get; set; }
public int Quantity { get; set; }
public virtual List<Order> orders { get; set; }
}
这是保存方法:
private void button1_Click(object sender, EventArgs e)
{
List<Product> p = new List<Product>();
foreach (Product item in listBox2.Items)
{
p.Add(item);
}
Variables.Db.orders.Add(new Order { account = Variables.Currentuser, products = p });
Variables.Db.SaveChanges(); //Variables.Db is my CodeFirst Database
}
我尝试了很多方法,例如:
int q = (listBox1.SelectedItem as Product).Quantity;
(listBox1.SelectedItem as Product).Quantity = (int)numericUpDown1.Value;
listBox2.Items.Add(listBox1.SelectedItem);
(listBox1.SelectedItem as Product).Quantity = q - (int)numericUpDown1.Value;
但最后一行将 listbox2 对象数量更改回与 listbox1s 相同。