I have a listbox with prices now I need to make a label to show the total off all the prices in that listbox. Now I need to make a variable to save every price that is entered in the listbox so then i show the total in the label.
Asked
Active
Viewed 789 times
-3
-
Well... just loop through the listbox's Items, but wouldn't it be easier to just sum it before binding the values to the listbox? – Feb 20 '14 at 16:48
2 Answers
0
You can iterate over all Items in ListBox
and sum it up.
Try This:
private void button1_Click(object sender, EventArgs e)
{
decimal total = 0;
foreach (var v in listBox1.Items)
{
total += Convert.ToDecimal(v);
}
label1.Text = total.ToString();
}

Sudhakar Tillapudi
- 25,935
- 5
- 37
- 67
-
[Don't use a `double` to store money, use `decimal`.](http://stackoverflow.com/questions/316727/is-a-double-really-unsuitable-for-money) – user247702 Feb 20 '14 at 16:49
-
the code is good but when for example make 80 and 80 in the listbox the label shows 240 as a total and not 160 – DannyFar94 Feb 20 '14 at 16:58
-
@user3328666: no dear it works fine, are you clearing the ListBox items before adding new items using `ListBox1.Items.Clear()` – Sudhakar Tillapudi Feb 20 '14 at 17:00
-
I made the items.clear after this code "label1.Text = total.ToString();" and the total is good but now the prices are not showing in the list box – DannyFar94 Feb 20 '14 at 17:06
-
@user3328666: no no , you should not clear the items everytime, what i meant was you need to clear your listbox items before adding new items , if you are only adding items once then you should not remove it, please share the code, i will look into it. – Sudhakar Tillapudi Feb 20 '14 at 17:07
0
You can use LINQ
var total = listBox1.Items.OfType<object>()
.Select(x => decimal.Parse(x.ToString())).Sum();
var label1.Text = total.ToString();

Selman Genç
- 100,147
- 13
- 119
- 184