How do I get the sum or total of the prices of items inside my list box?

Viewed 1313

The button 1-10 are the items; the pos screenshot

codes i used but doesn't work maybe it's wrong but i can't find answers on the internet

private void enterPayment_Click(object sender, EventArgs e)
{
    label1.Text = "Payment";
    //price.ReadOnly = false;
    //price.Text = "0.00";
    //price.Focus();

    //Kukunin ko yung total ng List Items
    double total = 0;
    int ilan = orders.Items.Count;

    for (int i = 0; i >= ilan; i++)
    {
        string item = orders.Items[i].ToString();
        int Index = item.IndexOf("@");
        int Length = item.Length;
        string presyoString = item.Substring(Index + 1, Length - Index - 1);
        double presyoDouble = double.Parse(presyoString);
        total += presyoDouble;
        //price.Text = (total + ".00");
    }
    price.Text = (total + ".00");
}
2 Answers

I strongly recommend that you use the listbox as a view only, not to be use to perform the mathematical operation. The data can be use in collection such as List so that you can perform better operation.

For example, at program load, I will add product information on List<T> and on form, I place a tag in the button consider it as product Id. So, when I click on the button, it will pass the tag property and from there, I will search the product information on list regarding my Id and add into another final List<T> and get the sum of it.

public partial class Form1 : Form
{
    private List<ProductDisplay> listProductDisplay = new List<ProductDisplay>();
    private List<ProductInformation> listProductInfo = new List<ProductInformation>();
    public Form1()
    {
        InitializeComponent();
        LoadProduct();

    }
    private void LoadProduct()
    {
        listProductDisplay = new List<ProductDisplay>()
        {
            new ProductDisplay{ProdID = 1,ProdName = "Chargrilled Burger",ProdPrice = 330.00m},
            new ProductDisplay{ProdID = 2,ProdName = "Mushroom N' Swish",ProdPrice = 330.00m},
            new ProductDisplay{ProdID = 3,ProdName = "Chicken Burger",ProdPrice = 250.00m},
            new ProductDisplay{ProdID = 4,ProdName = "Steak Loader",ProdPrice = 220.00m},
            new ProductDisplay{ProdID = 5,ProdName = "Cookie Sandwich",ProdPrice = 125.00m},
            new ProductDisplay{ProdID = 6,ProdName = "Cookie Sundae",ProdPrice = 175.00m},
            new ProductDisplay{ProdID = 7,ProdName = "Chicken Nuggets",ProdPrice = 145.00m},
            new ProductDisplay{ProdID = 8,ProdName = "Curly Fries",ProdPrice = 75.00m},
            new ProductDisplay{ProdID = 9,ProdName = "Sprite",ProdPrice = 50.00m},
            new ProductDisplay{ProdID = 10,ProdName = "Coke",ProdPrice = 50.00m}
        };
    }

    private void InsertOrder_ButtonClick(object sender, EventArgs e)
    {
        try
        {
            Button btn = (Button)sender;
            int number = Convert.ToInt32(btn.Tag);
            var itemProduct = listProductDisplay.First(x => x.ProdID == number);
            ProductInformation prod = new ProductInformation
            {
                ProdID = itemProduct.ProdID,
                ProdName = itemProduct.ProdName,
                ProdPrice = itemProduct.ProdPrice,
                ProdQty = 1

            };
            prod.ProdDisplayName = $"{prod.ProdQty}x {prod.ProdName} @{prod.ProdPrice.ToString("F")} = {(prod.ProdPrice * prod.ProdQty).ToString("F")}";
            listProductInfo.Add(prod);
            listBoxItem.DataSource = null;
            listBoxItem.DataSource = listProductInfo;
            listBoxItem.DisplayMember = "ProdDisplayName";
            listBoxItem.ValueMember = "ProdID";

            var price = listProductInfo.Sum(t => (t.ProdPrice * t.ProdQty));
            txtPayment.Text = price.ToString("F");
        }
        catch (Exception ex)
        {
            MessageBox.Show("Failed to insert order");
            throw;
        }
    }
}
public class ProductDisplay
{
    public int ProdID { get; set; }
    public string ProdName { get; set; }
    public decimal ProdPrice { get; set; }
}
public class ProductInformation
{
    public int ProdID { get; set; }
    public string ProdName { get; set; }
    public string ProdDisplayName { get; set; }
    public decimal ProdPrice { get; set; }
    public int ProdQty { get; set; }
}

enter image description here

Parsing and extracting values from a string like that is very error prone and brittle. What happens if the order of fields in your line changes? Or if you add currency symbols?

@Luiey's solution is the smartest way to go ahead. But if for some reason you cannot make so many changes to your code, the bare minimum you want to do is store the items in a list as a custom object with statically typed fields for price, quantity and total. The ListBox class invokes a ToString() at the time of rendering items. So you can easily override this method to prepare the output string according to your needs.

private class LineItem
{
    public LineItem()
    {
        Quantity = 0;
        Description = string.Empty;
        Price = 0;
    }

    public int Quantity
    {
        get;
        set;
    }

    public string Description
    {
        get;
        set;
    }

    public int Price
    {
        get;
        set;
    }

    public int Total
    {
        get
        {
            return Quantity * Price;
        }
    }

    public override string ToString()
    {
        return $"{Quantity} × {Description} @ {Price} = {Total}";
    }
}

Then you add an item to your ListBox like this.

var item = new LineItem()
{
    Quantity = 1,
    Description = "Foo bar",
    Price = 10
};
listBox1.Items.Add(item);

And add them up like this.

var items = listBox1.Items.Cast<LineItem>().ToArray();
var accumulator = 0;
accumulator = items.Aggregate(accumulator, (a, i) => a + (i.Quantity * i.Price), (a) => a);
Related