实现此目的的一种方法是,为您的项目创建一个 BindingList,遍历 BindingList 以查看新选择的项目是否在列表中,并根据此进行更新。
这是我所说的一个例子。
创建一个代表您的项目对象的类。
public class Item {
private readonly string name;
public string Name { get { return name; } }
public int Quantity { get; set; }
private readonly Decimal price;
public Decimal Price { get { return price; } }
public Item(string name, int qty, Decimal price) {
this.name = name;
this.Quantity = qty;
this.price = price;
}
public override string ToString() {
// You can mess with the formatting of it, this just provides an example
return string.Format("{0}\t{1}\t{2}", Quantity, name, Price * Quantity);
}
}
在您的表单中,创建一个BindingList<Item> 集合并为其创建一个DataSource。
BindingList<Item> items;
public Form1() {
InitializeComponent();
items = new BindingList<Item>();
listBox1.DataSource = items;
}
只需创建一个函数,将这些项目添加到您的BindingList
private void Update(Item newItem) {
bool found = false;
foreach (Item item in items) {
if (newItem.Name == item.Name) {
item.Quantity += newItem.Quantity;
found = true;
break;
}
}
if (!found) {
items.Add(newItem);
}
listBox1.DataSource = null;
listBox1.DataSource = items;
}
这应该能够更新您的ListBox每次您向其中添加项目。