vb.net For Each块有一个额外的运行(运行两次)

时间:2012-10-10 22:47:51

标签: asp.net vb.net loops foreach datatable

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

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

当我只有1行时,我可以使用exit关键字在1次运行后终止循环,但是现在我有超过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

1 个答案:

答案 0 :(得分: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()