Get value from DataTable

I want to get the entire column value from a DataTable and save it in a 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 this code, I got an error message:

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

so how to solve this problem ?? Please help me....

+6
source share
2 answers

You can try changing it to:

 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 should be one less than the row counter, since it is based on a zero index.

+10
source

It looks like you accidentally declared DataType as an array, not as a string.

Change line 3 to:

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

That should work.

+4
source

Source: https://habr.com/ru/post/905222/


All Articles