2011-06-16 112 views
2

我有一个DataGridView绑定到一个DataSet,它是由一个未知的设计时SQL查询返回的(呃,我知道查询是什么,我只是不知道哪个一个用户已经选择)。从DataGridViewSelectedRowCollection复制列详细信息

我允许用户从表中选择一组行并点击OK按钮,然后我想将这些行复制到新的DataGridView中。

天真,我使用的代码线沿线的:

DataGridView_New.DataSource = DataGridView_Old.SelectedRows 

这给了我一个行数在SelectedRows我的新的DataGridView等于行数,但列不是从列SQL查询(因为他们在DataGridView_Old);它们是每个单独行的Row属性(DefaultCellStyle,Resizable,ReadOnly等)。

是否有任何快速简单的方法来简单地从DataGridView_Old获取列数据并将选定的行复制到DataGridView_New

回答

1

这里有一个简单的方法可能你所需要的:

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; 
} 

我第一个冲动通过源是循环DGV的SelectedRows集合,但作为用户选择的行,不一定是一样的显示顺序,这些是有序的。

foreach (DataGridViewRow row in sourceDGV.SelectedRows) { 
    table.Rows.Add(((DataRowView)row.DataBoundItem).Row.ItemArray); 
} 
+1

谢谢,那就排序吧。不得不将我的数据加载函数打成一个兼容的形状,但我应该感谢您的解决方案激发了我将该DataTable传递到了我的第二个控件。 – Frosty840 2011-06-17 09:02:15

0

我不知道这是否会与数据集工作,但你可以尝试使用每个所选行的DataBoundItem属性来填充新的电网,像:

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; 
     } 
    }