vb.net将datatable加载到datagridview

时间:2012-08-11 15:54:15

标签: vb.net datagridview datatable

我使用以下代码从datagridview

生成数据表
 Dim t1 As New DataTable
 For Each col As DataGridViewColumn In DataGridView1.Columns
        t1.Columns.Add(col.HeaderText)
    Next

    For Each row As DataGridViewRow In DataGridView1.Rows
        Dim dRow1 As DataRow = t1.NewRow
                  For Each cell As DataGridViewCell In row.Cells
            dRow1(cell.ColumnIndex) = cell.Value
        Next
    Next

现在的问题是我如何将这个数据表加载到另一个datagridview?

2 个答案:

答案 0 :(得分:4)

Dim table As New DataTable
    ' Create four typed columns in the DataTable.
    table.Columns.Add("Dosage", GetType(Integer))
    table.Columns.Add("Drug", GetType(String))
    table.Columns.Add("Patient", GetType(String))
    table.Columns.Add("Date", GetType(DateTime))
    ' Add five rows with those columns filled in the DataTable.
    table.Rows.Add(25, "Indocin", "David", DateTime.Now)
    table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now)
    table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now)
    table.Rows.Add(21, "Combivent", "Janet", DateTime.Now)
    table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now)


    DataGridView1.DataSource = table


    DataGridView2.DataSource = table

如果您在一个数据网格中更改或添加行,则在另一个数据网格中更改。或者,如果更改代码并添加行,则会在datagrids上看到更改。

<强> UPDATE1:

如果您想从datagrid1获取数据并仅显示datagrid2中的数据:

Dim table1 As New DataTable
table1 = table.Copy()
DataGridView2.DataSource = table1

答案 1 :(得分:1)

您还需要

GridView1.DataBind()

GridView2.DataBind()

最后