how do i add the numbers in a listbox and display it in another textbox?

Dani AI

Generated

Good quick start from : that VB6 example works for small integer-only lists. Real-world lists often include decimals, empty entries or text, and items can be added/removed at runtime. The following notes and snippets show a safer, more robust approach (VB.NET), plus key pitfalls to avoid when summing listbox values.

A compact, safe VB.NET helper that sums all numeric items using Decimal.TryParse (no exceptions on bad input; good precision for money):

Private Function SumListBox(lb As ListBox) As Decimal
    Dim total As Decimal = 0D
    For Each itm As Object In lb.Items
        Dim s As String = Convert.ToString(itm)
        Dim v As Decimal
        If Decimal.TryParse(s, Globalization.NumberStyles.Number, Globalization.CultureInfo.CurrentCulture, v) Then
            total += v
        End If
    Next
    Return total
End Function

' Example display:
txtTotal.Text = SumListBox(ListBox1).ToString("N2")

To sum only selected items, use LINQ and the same TryParse pattern so non-numeric selections are ignored.

Troubleshooting and best practices:

  • Prefer Decimal over Integer to avoid overflow and to keep fractional precision. Avoid CInt when decimals may appear.
  • Use TryParse instead of direct casts to skip bad entries without runtime errors.
  • Call the sum helper immediately after adding, removing, or editing list items so the textbox stays in sync.
  • Watch culture-specific separators (comma vs dot); using CultureInfo.CurrentCulture keeps behavior consistent with the system locale.
  • In VB6, apply the same ideas: check IsNumeric and use CDbl rather than CInt for decimals; use ListCount to iterate.

These adjustments keep the UI robust and prevent crashes from unexpected list contents while producing correctly formatted totals.

Recommended Answers

All 2 Replies

how do i add the numbers in a listbox and display it in another textbox?

Create new project, add list1 and txtText1 to the form1 and paste:

Option Explicit

Private Sub Form_Load()
    Dim x As Integer
    Dim inx As Integer 'counter
    
    List1.AddItem "1"
    List1.AddItem "2"
    
    For inx = 0 To List1.ListCount - 1
        x = x + CInt(List1.List(inx))
    Next
    txtText1.Text = x
    
End Sub

thank u! :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.