I would recommend using an own class for your items. Something like
public class Item
{
public string Name { get; set; }
public int Price { get; set; }
public Item(string name, int price)
{
Name = name;
Price = price;
}
}
Instead of
listBox1.Items.Add("btnSoda.text");
you have to write
List<string> lines = File.ReadAllLines("btnSoda.text");
List<Item> items = new List<Item>();
foreach(string line in lines)
{
string[] parts = line.Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries);
string name = parts[0];
int price = int.Parse(parts[1]);
Item item = new Item(name, price);
items.Add(item);
}
comboBox1.DataSource = items;
With this piece of code you are reading your file and creating the Item items you want to show in your ComboBox. The advantage is that you have specific items with the properties you need and not a string which you have to interpret each time you want to do something with it.
Don't forget to set the DisplayMember property too name of your combobox. Otherwise you would not see the names of the items in your ComboBox.
After that you can use
int sum = comboBox1.Items
.OfType<Item>()
.Sum(x => x.Price);
label1.Text = sum.ToString();
to sum the prices.
Maybe it seems a bit more complicated then the other answer but it's the cleaner way.
Some advantages
- you will find out about errors in your textfile when you init your
ComboBox and not when calculating the sum
- you don't have to interpret your items each time you want to do something with 'em because you already did that at the start
- easier to understand and read: no magic strings or numbers