0
votes

Currently I am creating a Point-of-Sale system in C# that allows items to be added to a listbox at the click of a button. The information contained in each item is its name, quantity, and price which is displayed in the listbox.

The quantity and price of each item needs to be updated whenever another item of the same type is added. For example, if two cinnamon rolls are added to the order, the quantity should be updated from 1 to 2 as well as the total price for those two items. Also, the total of the items in the listbox should be updated each time a new item is added to the order.

The following is what I currently have for the GUI: Point of Sale image Any help or suggestions on how to go about this would be appreciated.

1
Welcome to Stack Overflow. :) Please note that this question as stated is too broad for the site. Please provide a minimal reproducible example that shows clearly what you've tried, along with a precise description of what that code does and how that's different from what you want it to do. Pleas also read How to Ask for advice on how to present your question in a clear, answerable way. - Peter Duniho

1 Answers

1
votes

One way you can achieve this, is by making a BindingList of your items, iterate over the BindingList to see if the new selected item is in the list, and update according.

Here is an example of what I am talking about.

Create a class which will represent your item objects.

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);
    }
}

In your form, create a BindingList<Item> collection and create a DataSourceto it.

BindingList<Item> items;

public Form1() {
    InitializeComponent();
    items = new BindingList<Item>();
    listBox1.DataSource = items;
}

And just create a function which will add these items to your 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;
}

This should be able to update your ListBoxeverytime you add an item to it.