【问题标题】:Adding and Changing Items in Listbox在列表框中添加和更改项目
【发布时间】:2015-11-22 03:43:54
【问题描述】:

目前我正在使用 C# 创建一个销售点系统,该系统允许通过单击按钮将项目添加到列表框中。每个项目包含的信息是它的名称、数量和价格,显示在列表框中。

每次添加同类型的其他商品时,都需要更新每件商品的数量和价格。例如,如果订单中添加了两个肉桂卷,则数量应从 1 更新为 2,以及这两个项目的总价。此外,每次向订单中添加新项目时,都应更新列表框中的项目总数。

以下是我目前用于 GUI 的内容: 任何有关如何解决此问题的帮助或建议将不胜感激。

【问题讨论】:

  • 欢迎来到 Stack Overflow。 :) 请注意,该问题对于该网站来说过于宽泛。请提供minimal reproducible example,清楚地显示您尝试过的内容,并准确描述该代码的功能以及与您希望它执行的操作有何不同。还请阅读How to Ask,了解如何以清晰、可回答的方式提出您的问题。

标签: c# listbox listboxitem


【解决方案1】:

实现此目的的一种方法是,为您的项目创建一个 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每次您向其中添加项目。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-05
    • 2020-08-12
    相关资源
    最近更新 更多