11

I want to get all column value from DataTable and store it to the ListBox. Here is my code

            If myTableData.Rows.Count > 0 Then
                For i As Integer = 0 To myTableData.Rows.Count
                    Dim DataType() As String = myTableData.Rows(i).Item(1)
                    ListBox2.Items.AddRange(DataType)
                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[]'

so, how to resolve this problem?? Please help me....

Flashidkz
  • 313
  • 4
  • 5
  • 13

2 Answers2

20

You can try changing it to this:

If myTableData.Rows.Count > 0 Then
  For i As Integer = 0 To myTableData.Rows.Count - 1
    ''Dim DataType() As String = myTableData.Rows(i).Item(1)
    ListBox2.Items.Add(myTableData.Rows(i)(1))
  Next
End If

Note: Your loop needs to be one less than the row count since it's a zero-based index.

LarsTech
  • 80,625
  • 14
  • 153
  • 225
8

It looks like you have accidentally declared DataType as an array rather than as a string.

Change line 3 to:

Dim DataType As String = myTableData.Rows(i).Item(1)

That should work.

Richard
  • 1,122
  • 1
  • 7
  • 14