Moko
Moko

Reputation: 5

Error when displaying database table data to listview on VB.Net

I'm using vb.net 2013 and database sql server express. When i try to displaying database to listview, i get error like this

An unhandled exception of type 'System.Reflection.AmbiguousMatchException' occurred in Microsoft.VisualBasic.dll Additional information: Overload resolution failed because no Public 'Add' can be called with these arguments: 'Public Function Add(item As System.Windows.Forms.ListViewItem.ListViewSubItem) As System.Windows.Forms.ListViewItem.ListViewSubItem': Argument matching parameter 'item' cannot convert from 'DBNull' to 'ListViewSubItem'. 'Public Function Add(text As String) As System.Windows.Forms.ListViewItem.ListViewSubItem': Argument matching parameter 'text' cannot convert from 'DBNull' to 'String'.

And my code like this :

Sub ListViewForMasterBiaya()
    Call DatabaseConnection()
    Dim DT As New DataTable
    Dim DS As New DataSet
    CMD = New SqlCommand("SELECT * FROM EntriBiaya", CONN)
    DA = New SqlDataAdapter(CMD)
    DS.Clear()
    DA.Fill(DS, "EntriBiaya")
    DT = DS.Tables(0)
    ListViewMasterBiaya.Items.Clear()
    For i As Integer = 0 To DT.Rows.Count - 1
        With ListViewMasterBiaya
            .Items.Add(DT.Rows(i)("NoKode"))
            With .Items(.Items.Count - 1).SubItems
                .Add(DT.Rows(i)("JenisBiaya"))
                .Add(DT.Rows(i)("NoPol"))
                .Add(DT.Rows(i)("Debit"))
                .Add(DT.Rows(i)("Kredit"))
                .Add(DT.Rows(i)("Tabungan"))
                .Add(DT.Rows(i)("Angsuran"))
                .Add(DT.Rows(i)("Klaim"))
                .Add(DT.Rows(i)("TotalDiterima"))
            End With
        End With
    Next
End Sub

And the error shows in line 19. Is something wrong? Please help

Upvotes: 0

Views: 410

Answers (1)

jmcilhinney
jmcilhinney

Reputation: 54417

The specific issue is that, while some of your fields do contain a String and the abovementioned cast/conversion can be done implicitly, at least one field is NULL and thus contains DBNull.Value, which is not a String or any other type that that Add method is expecting, which is what the error message is telling you. If you expect to pass a String to Add when the field is NULL then you need to create one.

The easiest option is to simply call ToString on the Object reference you get from the DataRow. That will handle data that is already a String, other types of data and NULLs too, because DBNull.ToString() returns String.Empty, e.g.

.Add(DT.Rows(i)("TotalDiterima").ToString())

Upvotes: 2

Related Questions