Copy column details from DataGridViewSelectedRowCollection
I've got a DataGridView which is bound to a DataSet being returned by an unknown-at-design-time SQL query (well, I know what the queries are, I just don't know which one the user has selected).
I allow the user to select a set of rows from the table and hit an OK button, and I would then like to copy those rows to a new DataGridView.
Naively, I used code along the lines of:
DataGridView_New.DataSource = DataGridView_Old.SelectedRows
This gives me a number of rows in my new DataGridView equal to the number of rows in SelectedRows
, but the columns are not the columns from the SQL query (as they were in DataGridView_Old
); they are, instead, the Row prope开发者_JAVA技巧rties of each of the individual rows (DefaultCellStyle, Resizable, ReadOnly, etc.).
Is there any quick and easy way to simply grab the column data from DataGridView_Old
and copy the selected rows into DataGridView_New
?
Here's a simple method that might do what you need:
private void CopySelectedRows(DataGridView sourceDGV, DataGridView destDGV) {
// Clean up any previous runs.
destDGV.DataSource = null;
destDGV.Columns.Clear();
// Populate the destination DGV with the same columns found in the source DGV.
foreach (DataGridViewColumn col in sourceDGV.Columns) {
destDGV.Columns.Add(col.Clone() as DataGridViewColumn);
}
// Create a DataTable that has the same structure as the source DGV's DataSource DataTable.
DataTable table = ((DataTable)sourceDGV.DataSource).Clone();
// Use the data bound to the selected rows in the source DGV to create rows in your DataTable.
foreach (DataGridViewRow row in sourceDGV.Rows) {
if (row.Selected) {
table.Rows.Add(((DataRowView)row.DataBoundItem).Row.ItemArray);
}
}
destDGV.DataSource = table;
}
My first impulse was to loop through the source DGV's SelectedRows collection but these are ordered as the user selected the rows, not necessarily the same as the displayed order.
foreach (DataGridViewRow row in sourceDGV.SelectedRows) {
table.Rows.Add(((DataRowView)row.DataBoundItem).Row.ItemArray);
}
I'm not sure if it will work with DataSets, but you could try using the DataBoundItem property of each selected row to populate the new grid, something like:
public void Populate()
{
var selectedRows = GetRows(DataGridView_Old.SelectedRows);
DataGridView_New.DataSource = selectedRows
.Select(r => r.DataBoundItem).ToList();
}
public IEnumerable<DataGridViewRow> GetRows(DataGridViewSelectedRowCollection rows)
{
foreach (DataGridViewRow row in rows)
{
yield return row;
}
}
精彩评论