-
Jul 22nd, 2021, 09:39 PM
#1
Thread Starter
Frenzied Member
[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...
-
Jul 22nd, 2021, 09:49 PM
#2
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:
Dim total As Double
For Each item As DataRowView In ListBox1.Items
total += CDbl(item("amount"))
Next
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|