我正在将数据表内容转换为字符串,假设数据集有12行和8列。 最后,Dict包含12行或96列。我的代码下面有什么问题,如何重置行?
蒂亚。
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
答案 0 :(得分:4)
您应该为每个row
重新初始化dr
,实际上您无需在row
循环之外声明dr
。
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