Gian
Gian

Reputation: 674

Loop DataColumns in DataRow

I am converting data table content to string, Say the dataset has 12 rows and 8 column. At the end, the Dict contain 12 rows or 96 columns. what's wrong with my code below, how do I reset the row?

Tia.

        Dim ds As DataSet = ClsDB.GetDataSet(sql)

    If Not ds Is Nothing AndAlso ds.Tables.Count > 0 Then
        Dim row As New List(Of KeyValuePair(Of String, String))
        Dim dict As New List(Of KeyValuePair(Of Integer, Object))
        Dim dt As DataTable = ds.Tables(0)
        Dim i As Integer = 0 

        For Each dr As DataRow In dt.Rows 
            For Each dc As DataColumn In dt.Columns
                row.Add(New KeyValuePair(Of String, String)(dc.ColumnName, IIf(Not IsDBNull(dr.Item(dc.ColumnName)), dr.Item(dc.ColumnName), "")))
            Next
            dict.Add(New KeyValuePair(Of Integer, Object)(i, row))
            i += i 
        Next

        Return New JavaScriptSerializer().Serialize(dict)
    Else
        Return "No Data"
    End If

Upvotes: 2

Views: 25149

Answers (1)

Jodrell
Jodrell

Reputation: 35696

You should reinitialise row for every dr, in fact you needn't declare row outside the dr loop.

For Each dr As DataRow In dt.Rows
    Dim row As New List(Of KeyValuePair(Of String, String))   // <<-         
    For Each dc As DataColumn In dt.Columns                 
        row.Add(...
    Next             
    dict.Add(...
Next

Upvotes: 4

Related Questions