balaji
balaji

Reputation: 57

Returning datas from datatable in vb.net

DTName is a DataTable which returns rows in the code below...when I iterate it through the loop from 0 to its count. Only the data in first row is displayed.

How to get all the rows of the datatable displayed in the result ?

DTName = GetClientNames()

   If Not DTName Is Nothing Then

      For i = 0 to DTName.Rows.count

         strName = DTName.Rows(i).Item("Client Name").Tostring()

      Next i

   End if

Upvotes: 0

Views: 1756

Answers (2)

Abdusalam Ben Haj
Abdusalam Ben Haj

Reputation: 5423

For i = 0 to DTName.Rows.count would eventually throw a IndexOutOfRangeException error when the value of i equals to DTName.Rows.count, the limit should be DTName.Rows.count - 1 .

To get all the values from all datarows, store them in a List :

    Dim strName As New List(Of String)

    For i = 0 to DTName.Rows.count - 1

       strName.Add(DTName.Rows(i)("Client Name").Tostring())

    Next i

Alternatively you could use Foreach like this :

    For Each DR As DataRow In DTName.Rows

       strName.Add(DR("Client Name").Tostring())

    Next

I also suggest you remove the redundant check if DTName.Rows.Count > 0

EDIT : You could Declare strName as string and append row values to it :

    For i = 0 to DTName.Rows.count - 1

        strName &= (DTName.Rows(i)("Client Name").Tostring() & ",")

    Next i

    Response.Write(strName)

Upvotes: 3

spajce
spajce

Reputation: 7082

Double to check the actual ColumnName of the Column.

For Each item As DataRow In dataTable.Rows
    strName = item("Client Name").ToString()
    Console.WriteLine(strName)
Next

Upvotes: 0

Related Questions