3
votes

I want to use the user-selected rows from one DataGridView as the DataSource for a second DataGridView. Note both DataGridViews will have identical columns.

Obviously I can iterate over the selected rows, obtain the key values, and re-query the database for a List to use as the DataSource of the 2nd grid, but that seems lame.

Surely there is an elegant way of simply re-using the SelectedRows collection as a DataSource?

3
SelectedRows is a simple collection without notifications (compared to BindingSource), so you will have to in any case handle event when it's changed (rised by DataGridView) to at least update BindingSource.Sinatr

3 Answers

2
votes

You cannot directly set collection of DataRow as datasource, you can read more details from MSDN

How about doing (bit) traditional way?

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;
0
votes

Another way to do this using CopyToDataTable method.

DataTable dtable2;
DataRow[] rowArray = dataGridView1.SelectedRows;
If !(rowArray.Length == 0 )
{
    dTable2 = rowArray.CopyToDataTable();
}

dataGrodView2.DataSource = dTable2;
0
votes

Thanks for your replies. Seems there isn't a very simple way.

I did it this way:

MyDatGridView.SelectedRows.Cast<DataGridViewRow>().Select(dgvr => (int)dgvr.Cells[0].Value).ToList());

Then I tried to use the resulting List with a .Contains in a .Where clause.