简体   繁体   中英

How to sum all the numbers in the listbox

I want to sum all the numbers in the listbox , the numbers are from the database the date type is money ,and in every time i click the button i want to show the summed of the numbers in the list box .

the code i use :

decimal sum = 0;

private void but_TotalSale_Click(object sender, EventArgs e)
        {

            for (int i = 0; i < lst_Price.Items.Count; i++)
            {
                sum += Convert.ToDecimal(lst_Price.Items[i].ToString());
            }

            textBox1.Text = Convert.ToString(sum);
        }

And I'm getting this Error

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

Additional information: Input string was not in a correct format.

how to do it ? and how to fix the Error.

the listbox enter image description here

I think the issue is you're converting the listitem to a string not using the value inside the list item.

Try this:

decimal sum = 0; 
private void but_TotalSale_Click(object sender, EventArgs e) { 
for (int i = 0; i < lst_Price.Items.Count; i++) { 
     sum += Convert.ToDecimal(lst_Price.Items[i].Text);
  } 
textBox1.Text = Convert.ToString(sum); 
}

why you are converting to string in the first place

lst_Price.Items[i] is an object and Convert.ToDecimal() has an overload which can get an object

so can do

  for (int i = 0; i < listBox1.Items.Count; i++)
            {
                sum += Convert.ToDecimal(lst_Price.Items[i]);
            }

or in one line with LINQ

sum = lst_Price.Items.OfType<object>().Sum(x => Convert.ToDecimal(x));

your code is correct. Inside a list Box if there have any text ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM