0

I just want to know how to get the total value.

here's an example inside the listbox:

Soda - 30
Food - 50 

How can I sum the 30 and 50 and show it on a textbox? Please help. My code for adding to listbox is:

listBox1.Items.Add("btnSoda.text");

and my code for button that will get the total value:

int i = 0, result = 0;
while (i < listBox1.Items.Count)
{           
    result += Convert.ToInt32(listBox1.Items[i++]);
}

textboxtotal.Text = Convert.ToString((double)result)

after I run the program and click on getTotal Value it shows an error:

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll

6
  • Create an Item class which has two properties, for example: ItemName, and ItemPrice, and after that you can iterate through the listbox items and sum the price values. Commented Aug 1, 2017 at 11:57
  • Check this. You have to create key value pair. Then you can add the same by using values. Commented Aug 1, 2017 at 11:58
  • can you give me an example in code form? im sorry im just a newbie who is willing to learn. Thank you very much :) @C1sc0 Commented Aug 1, 2017 at 11:58
  • @Lifewithsun KeyValue pair is a bad choice. Use a own class instead (see C1sc0) because it's the cleaner way and better to read. Commented Aug 1, 2017 at 11:59
  • Are you using WPF, winforms or something else? Commented Aug 1, 2017 at 12:00

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

You can use Split() and Sum():

var sum = listBox1.Items
         .OfType<string>()
         .Select(s => Convert.ToInt32(s.Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries)[1]))
         .Sum();

and then:

lbltotal.Text = sum.ToString();

Also, you can change your code a little and it should work:

while (i < listBox1.Items.Count)
{           
    result += Convert.ToInt32(((string)listBox1.Items[i++]).Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries)[1]);
}

4 Comments

If he is a beginner, definitely he will get confused with this piece of code, But nice and quick, I hope you should take the first index instead for second, that means s.Split(..)[2] should be s.Split(..)[1]
can i ask where will i put this codes? thank you for answering :)
@Mark, simply replace your code with whileloop by this
@RomaDoskoch thank you very much it works! i've accept your answer! Thank you again :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.