radders
radders

Reputation: 923

Use DataGridView.SelectedRows as DataSource for another DataGridView

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?

Upvotes: 3

Views: 1898

Answers (3)

radders
radders

Reputation: 923

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.

Upvotes: 0

aspiring
aspiring

Reputation: 1647

Another way to do this using CopyToDataTable method.

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

dataGrodView2.DataSource = dTable2;

Upvotes: 0

Hari Prasad
Hari Prasad

Reputation: 16956

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;

Upvotes: 2

Related Questions