如何更新列表中的e特定值.. 例如,当我点击一个按钮时,它会在列表中添加产品
名称:coffe ||数量:1 ||价格:$ 2
当我点击相同产品时数量增加1 我使用了这段代码,但它并没有改变数量。
private BindingList<recipt> Lista2 = new BindingList<recipt>();
private void addtolist(object sender, EventArgs e)
{
Button b = (Button)sender;
Product p = (Product)b.Tag;
recipt fat = new recipt ()
{
Name= p.Name,
quantity= 1,
price = p.Cmimi
};
bool found = false;
if (listBox1.Items.Count > 0)
{
foreach (var pr in Lista2)
{
if (pr.Name== p.Name)
{
pr.quantity= pr.quantity+ 1;
found = true;
}
}
if (!found)
{
fat.tot= fat.quantity* fat.price;
fat.Nr_bill = Convert.ToInt32(txtNrbill.Text);
Lista2.Add(fat);
}
}
else
{
fat.tot= fat.quantity* fat.price;
fat.Nr_bill = Convert.ToInt32(txtNrbill.Text);
Lista2.Add(fat);
}
fat.tot= fat.quantity* fat.price;
fat.Nr_bill = Convert.ToInt32(txtNrbill.Text);
Lista2.Add(fat);
pe.Faturs.Add(fat);
pe.SaveChanges();
Total = Total + (int)fat.price;
listBox1.SelectedIndex = listBox1.Items.Count - 1;
}
答案 0 :(得分:0)
要自动更新ListBox中的值,您需要将BindingList
收据设置为ListBox.DataSource
并使Receipt
类实现INotifyPropertyChanged
public class Receipt : INotifyPropertyChanged
{
public string Name { get; }
public int Quantity { get; private set; }
public decimal Price { get; }
public string BillNumber { get; private set; }
public decimal Total => Price * Quantity;
public string Info => $"{nameof(Name)}: {Name} || {nameof(Quantity)}: {Quantity} || {nameof(Price)}: {Price:C} || {nameof(Total)}: {Total:C}";
public Receipt(string name, decimal price, string billNumber)
{
Name = name;
Price = price;
BillNumber = billNumber;
Quantity = 1;
}
public void AddOne()
{
Quantity += 1;
RaisePropertyChanged(nameof(Info));
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void RaisePropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
然后以表格
public class YourForm : Form
{
private readonly BindingList<Receipt> _Receipts;
public YourForm()
{
_Receipts = new BindingList<Receipt>();
listBox1.DisplayMember = "Info";
listBox1.DataSource = _Receipts;
}
private void AddToList(object sender, EventArgs e)
{
var button = (Button) sender;
var product = (Product) button.Tag;
var receiptInfo = _Receipts.FirstOrDefault(receipt => receipt.Name.Equals(product.Name));
if (receiptInfo == null)
{
receiptInfo = new Receipt(product.Name, product.Cmimi, txtNrbill.Text);
_Receipts.Add(receiptInfo);
}
else
{
receiptInfo.AddOne();
}
}
}