0

我有一个数据表,我想将一行转换为包含所有列名的单个字符串,因此格式如下:column1_name:column1_content。column2_name:column2_content...

我几乎按照我想要的方式完成了它,除了结果将是相同的字符串重复两次。例如,字符串“abc”是我想要的,但它会返回“abcabc”。

当我只有 1 行时没关系,我可以在 1 次运行后使用 exit 关键字终止循环,但现在我有超过 1 行的数据表,这是出乎意料的,所以循环必须完成。请帮我找出原因。谢谢。

这是代码:

    Dim column As New DataColumn
    Dim dt As New DataTable
    dt.Load(dr)

    For Each row As DataRow In dt.Rows
        Dim i As Integer = 0
        For Each column In dt.Columns
            If Not IsDBNull(row.ItemArray.GetValue(i)) Then
                sData = sData & column.ColumnName & ": " & row.ItemArray.GetValue(i).ToString & ". " & vbLf
            End If
            i = i + 1
        Next
    Next
4

1 回答 1

0

尝试这个

'set up dummy data
Dim dtb As New DataTable
dtb.Columns.Add(New DataColumn("Col0", GetType(String)))
dtb.Columns.Add(New DataColumn("Col1", GetType(String)))
dtb.Columns.Add(New DataColumn("Col2", GetType(String)))
dtb.Rows.Add("R0C0", "R0C1", "R0C2")
dtb.Rows.Add("R1C0", "R1C1", "R1C2")
'extract rows
Dim sbl As New System.Text.StringBuilder
For intRow As Integer = 0 To dtb.Rows.Count - 1
  Dim drw As DataRow = dtb.Rows(intRow)
  For intCol As Integer = 0 To dtb.Columns.Count - 1
    If drw.Item(intCol) IsNot Nothing Then
      sbl.AppendLine("Row " & intRow.ToString & " " & dtb.Columns(intCol).ColumnName & ": " & drw.Item(intCol).ToString & ". ")
    End If
  Next intCol
Next intRow
MsgBox(sbl.ToString)
dtb.Dispose()
于 2012-10-11T02:10:18.617 回答