Getting the sum of the items in a lstBox

Hekzdaddy 121 Reputation points
2021-03-14T01:27:40.217+00:00

Hello all, I have an annoying issue I can't figure out. I have several numbers in a lstBox that I want to return on a lblTotal. I am using a For...Next type statement. For intCount = 0 To lstCost.Items.Count - 1 Next I've made some attemp by using : 'lblTotal.Text = (+lstCost.Items(intCount).ToString()) ' lblTotal.Text = +declstCost.ToString(intCount).ToString But I cant figure it out.

Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
4,603 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 112.1K Reputation points
    2021-03-14T09:05:13.277+00:00

    This should work:

    lblTotal.Text = "0"
    For intCount = 0 To lstCost.Items.Count - 1
        lblTotal.Text += +lstCost.Items(intCount)
    Next
    

    But if you add the ‘Option Strict On’ line to the beginning of your file to make more reliable programs, then consider this alternative too:

    Dim sum As Integer = 0
    For Each item In lstCost.Items
        Dim n As Integer
        If Integer.TryParse(item.ToString, n) Then sum += n
    Next
    lblTotal.Text = sum.ToString
    

    or something like this:

    lblTotal.Text = lstCost.Items.Cast(Of Object) _
        .Sum(Function(item)
                    Dim n As Integer
                    Integer.TryParse(item.ToString, n)
                    Return n
                End Function).ToString
    

4 additional answers

Sort by: Most helpful
  1. Hekzdaddy 121 Reputation points
    2021-03-14T18:07:53.953+00:00

    the first one worked perfectly, would you be so kind to explain how I can show that total as a currency w/ decimal?


  2. Hekzdaddy 121 Reputation points
    2021-03-14T18:30:43.56+00:00

    sum is not declared error


  3. Hekzdaddy 121 Reputation points
    2021-03-14T18:34:08.95+00:00

    How can I follow you, you've been very helpful. Are you able to explain certain information when I need help? I am taking my first programming class that revolves around Visual Studio/basics

    0 comments No comments

  4. Hekzdaddy 121 Reputation points
    2021-03-14T22:36:42.39+00:00
        decTotalCost = intNumDays * decLocationFee + decRegistrationFee
        lstCost.Items.Add(decTotalCost).ToString("c")
    

    mt lstCost is not displaying the numbers as ("c") or decimal, any thoughts?

    0 comments No comments