Results 1 to 2 of 2

Thread: [RESOLVED] sum listbox items

  1. #1

    Thread Starter
    Frenzied Member toecutter's Avatar
    Join Date
    Apr 2006
    Location
    Brisbane, Australia
    Posts
    1,144

    Resolved [RESOLVED] sum listbox items

    Iam adding a elemnet from a xml file into listbox
    Code:
    Option Strict On
    Option Explicit On
    Option Infer Off
    Imports System.IO
    Imports System.Xml
    Imports System.Net
    Imports System.Windows.Forms.VisualStyles.VisualStyleElement.ListView
    
    Public Class Form1
        Dim path As String = ("F:\ESS_Contacts\dsContactsSUBS.xml")
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        End Sub
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim ds As New DataSet
            ds.ReadXml(path)
            ListBox1.DataSource = ds.Tables("Contacts")
            ListBox1.DisplayMember = "amount"
        End Sub
    
        Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
            Dim totall As Double
            For Each item As Double In ListBox1.Items
                totall += item
            Next
            txtTotalCost.Text = CType(totall, String)
    
        End Sub
    End Class
    I am then trying to sum the list but keeping getting errors

    System.InvalidCastException: 'Conversion from type 'DataRowView' to type 'Double' is not valid.'

    I have worked out its because of the way i add the data

    Ive tried heaps of examples but always get the same error.

    ps. ignore images, seems to be no way to delete once uploaded...
    Attached Images Attached Images   

  2. #2
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    107,478

    Re: sum listbox items

    Firstly, set the DataSource last when binding.

    As for the issue, when you bind a DataTable, the data comes from its DefaultView, which is type DataView, which contains DataRowView objects. That's why you get the error message about that type. Each item is an object of that type and the DisplayMember tells the control which column to get data from to display. In your case, it's the 'amount' column. If you want that data then you actually have to get that data. That means getting the data from that column yourself or getting it from the text of each item and converting it back to its original type:
    vb.net Code:
    1. Dim total As Double
    2.  
    3. For Each item As DataRowView In ListBox1.Items
    4.     total += CDbl(item("amount"))
    5. Next
    6.  
    7. txtTotalCost.Text = total.ToString()

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width