Use DataGridView.SelectedRows as DataSource for another DataGridView
I want to use user selected rows from one DataGridView as the data source for the second DataGridView. Note that both DataGridViews will have the same columns.
Obviously I can iterate over the selected rows, get the key values, and re-query the database for the list to be used as the second grid's data source, but that seems lame.
Surely there is an elegant way to just reuse the SelectedRows collection as a data source?
+3
source to share
3 answers
You cannot directly set a collection DataRow
as data source, you can read more details fromMSDN
How to do the traditional way (bit)?
var dt = ((DataTable)dataGrid1.DataSource).Clone();
foreach (DataGridViewRow row in dataGrid1.SelectedRows)
{
dt.ImportRow(((DataTable)dataGrid1.DataSource).Rows[row.Index]);
}
dt.AcceptChanges();
dataGrid2.DataSource = dt;
+2
source to share
Another way to do this is with the CopyToDataTable method .
DataTable dtable2;
DataRow[] rowArray = dataGridView1.SelectedRows;
If !(rowArray.Length == 0 )
{
dTable2 = rowArray.CopyToDataTable();
}
dataGrodView2.DataSource = dTable2;
0
source to share