Summing items in listbox

84 views Asked by At

I am having trouble with this math problem:

lsamount.Items.Add(String.Format("{0:n}", Val(exp_amount.Text)))

In my Timer code:

For i = 0 To lsamount.Items.Count - 1
   TOT = TOT + Val(lsamount.Items(i))
Next i
totalamount.Text = TOT.ToString

Is there any simplest way to add this 2?

3

There are 3 answers

2
Trevor On BEST ANSWER

Here's another suggestion and only one line of code and no looping... This uses Linq to accomplish this.

 totalamount.Text = lsamount.Items.Cast(Of String)().Sum(Function(x) Convert.ToDouble(x.Replace(",", ""))).ToString
0
Denver On

i think i nailed it here is my new timer code

        Dim TOT As Double
        Dim tmpstr As String
        For i = 0 To lsamount.Items.Count - 1
            tmpstr = lsamount.Items(i).ToString.Replace(",", "")

            TOT = TOT + Val(tmpstr)
        Next i
        totalamount.Text = (String.Format("{0:n}", Val(TOT)))

its working fine.

1
Siamak Ferdos On

Try this:

totalamount.Text = string.Join("", lsamount.Items)