Vb.net – DataTable to ArrayList

arraylistdatatablevb.net

I want to get value from datatable and then store it to the string() arraylist. datatable contain 3 column (columnA | columnB | columnC). I want to get all value from columnB and store it to arraylist.

I have try something like this

If myTableData.Rows.Count > 0 Then
    For i As Integer = 0 To myTableData.Rows.Count - 1
        Dim value() As String = myTableData.Rows(i)(1)
    Next
End If

but when I compile that code, I got error message like this :

Unable to cast object of type 'System.String' to type 'System.String[]'

please help me…..

Best Solution

You could do that with LINQ:

Dim colBValues = (From row In myTableData Select colB = row(1).ToString).ToList

Or if you prefer the "old-school" way:

Dim colBValues = New List(Of String)
For Each row As DataRow In myTableData.Rows
    colBValues.Add(row(1).ToString)
Next

I've used a List(Of String) because it's type-safe, therefore you don't need to cast the values everytime. That makes code more readable, more failsafe and faster.

If you need it as String-Array, you could simply use ToArray:

Dim colBValues = (From row In myTableData Select colB = row(1).ToString).ToArray