如何翻转数据集并在datagridview中显示

时间:2016-07-09 13:33:58

标签: vb.net datagridview dataset

我尝试使用此代码翻转数据集以将列显示为行,但它不起作用:

 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button.Click
    Dim ds2 As New DataSet
    Dim dt2 As New DataTable
    Dim com1 As String = "select  col1,col2,col3 from table1"
    ds2 = FlipDataSet(ds2)
    Dim dp As New SqlDataAdapter(com1, conn)
    dp.Fill(dt2)
    DGV_lev1.DataSource = dt2.DefaultView
End Sub

并使用此功能翻转数据集:

Private Function FlipDataSet(old_DataSet As DataSet) As DataSet

    Dim ds As New DataSet()
    For Each dt As DataTable In old_DataSet.Tables
        Dim table As New DataTable()
        For i As Integer = 0 To dt.Rows.Count
            table.Columns.Add(Convert.ToString(i))
            table.Columns(0).ColumnName = "Fields"
            If i = 0 Then
                Continue For
            Else

                table.Columns(i).ColumnName = "Customer " & i
            End If
        Next
        Dim r As DataRow
        For k As Integer = 0 To dt.Columns.Count - 1
            r = table.NewRow()
            r(0) = dt.Columns(k).ToString()
            For j As Integer = 1 To dt.Rows.Count
                r(j) = dt.Rows(j - 1)(k)
            Next
            table.Rows.Add(r)
        Next
        ds.Tables.Add(table)
    Next
    Return ds
End Function

从中显示datagirdview:

enter image description here

到此:

enter image description here

任何人都可以帮助我

谢谢

1 个答案:

答案 0 :(得分:1)

试试这个,它在我做的快速测试中起作用:

Private Function Transpose(ByVal table As DataTable) As DataTable
    Dim flippedTable As New DataTable
    'creates as many columns as rows in source table
    flippedTable.Columns.AddRange(
        table.Select.Select(
            Function(dr) New DataColumn("col" & table.Rows.IndexOf(dr), GetType(Object))
            ).ToArray)
    'iterates columns in source table
    For Each dc As DataColumn In table.Columns
        'get array of values of column in each row and add as new row in target table
        flippedTable.Rows.Add(table.Select.Select(Function(dr) dr(dc)).ToArray)
    Next
    Return flippedTable
End Function