我有一个DataGridView绑定到一个DataSet,由一个未知的设计时SQL查询返回(好吧,我知道查询是什么,我只是不知道用户选择了哪一个) )。
我允许用户从表中选择一组行并点击OK按钮,然后我想将这些行复制到新的DataGridView。
天真地,我使用了以下代码:
DataGridView_New.DataSource = DataGridView_Old.SelectedRows
这给了我新的DataGridView中的行数等于SelectedRows
中的行数,但是这些列不是SQL查询中的列(就像它们在DataGridView_Old
中一样);相反,它们是每个行的Row属性(DefaultCellStyle,Resizable,ReadOnly等)。
是否可以通过简单方法从DataGridView_Old
中获取列数据,并将所选行复制到DataGridView_New
?
答案 0 :(得分: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 :(得分:0)
我不确定它是否适用于DataSet,但您可以尝试使用每个选定行的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;
}
}