Roadside Romeozz
Roadside Romeozz

Reputation: 83

DataTable to list in VB.Net

I have a list

Public Class Payment
    Public Property Payments As List(Of PaymentArr)
End Class

Public Class PaymentArr
    Public Property Invoice_Num As String
    Public Property Invoice_Date As String
    Public Property GL_Date As String
End Class

and I have a table

Inv_Num    Inv_Date    GL_Date
 1          20200606    20200606
 2          20200607    20200607
 3          20200608    20200608

I need to convert above table into Payments List, please advise what to do

Upvotes: 0

Views: 4388

Answers (1)

Jon Roberts
Jon Roberts

Reputation: 2282

This function should do it:

Public Function ConvertTableToList(dt As DataTable) As List(Of PaymentArr)

    Dim payments As New List(Of PaymentArr)
    For Each rw As DataRow In dt.Rows
        Dim payment As New PaymentArr With
        {
          .Invoice_Num = rw.Item("Inv_Num"),
          .Invoice_Date = rw.Item("Inv_Date"),
          .GL_Date = rw.Item("GL_Date")
        }
        payments.Add(payment)
    Next

    Return payments

End Function

Call it as follows:

Dim pymnt As New Payment
pymnt.Payments = ConvertTableToList(myDatatable)

where myDatatable is the table containing your data

There will be shorter / neater solutions using LINQ but this version should be easy for you to follow

Upvotes: 1

Related Questions