Search code examples
vb.netlistdatatables

How do you convert a Data Table Column to a List of string in VB.Net


I have a Data Table with one column in it. I want to take that Data Table column and either convert it straight into a list of string.

I have tried using a For Each loop to get each data row item and write it to a list of string but when I'm looking at the output after using a Write Line, I get "System.Data.DataRow" instead of the row value which would be something like "11363".

Here is the data table. The row title is "Codes". The values below the column title are what I want added to a list of string.

[Codes
11361
11362
11363
15509
16494
16898
17333
19550
]

Here is the code that I have tried to use that is not working for me.

ForEach row As DataRow in ExampleDataTable
    If Not String.IsNullOrEmpty(row.ToString.Trim)
        ExampleList.Add(row.ToString)
    End If
Next

ForEach item As String in ExampleList
    Console.WriteLine(item)
Next

The output I get from that after using a For Each loop to print out everything in the list is:

System.Data.DataRow
System.Data.DataRow
System.Data.DataRow
System.Data.DataRow
System.Data.DataRow
System.Data.DataRow
System.Data.DataRow
System.Data.DataRow

What I want it to output is:

11361
11362
11363
15509
16494
16898
17333
19550

Can anyone help me out with this? I've read a lot of posts now on Stack Overflow as well as MSDN and I'm just not able to figure this one out.


Solution

  • Don't add the whole row. Add the column by using row.item(colName or ColNumber)

    Dim ExampleList As New List(Of String)
    For Each row As DataRow In ExampleDataTable.Rows
        If Not String.IsNullOrEmpty(row.Item("Codes")) Then
            ExampleList.Add(row.Item("Codes").ToString)
        End If
    Next
    

    EDIT: Code above now corrected to compile OK. A LINQ version would be:

    Dim ExampleList = (From rw As DataRow In ExampleDataTable.Rows
                       Where Not String.IsNullOrEmpty(rw.Item("Codes"))
                       Select rw.Item("Codes")
                       ).ToList()