user1590636 user1590636 - 3 months ago 53
Vb.net Question

vb.net load datatable to datagridview

I use the following code to generate a data table from 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


Now the question is how do i load this datatable to another datagridview ?

Answer
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

if you change or add rows in one datagrid it changed in other one. or if you change in code and add rows you see the changes on datagrids.

Update1:

if you want to get data from datagrid1 and show only that data in datagrid2 use :

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