.net 从DataGridViewSelectedRowCollection复制列详细信息
我有一个DataGridView,它绑定到一个由未知的设计时SQL查询返回的数据集(我知道这些查询是什么,只是不知道用户选择了哪一个) 我允许用户从表中选择一组行并点击OK按钮,然后我想将这些行复制到新的DataGridView 我天真地使用了以下代码:.net 从DataGridViewSelectedRowCollection复制列详细信息,.net,winforms,datagridview,.net,Winforms,Datagridview,我有一个DataGridView,它绑定到一个由未知的设计时SQL查询返回的数据集(我知道这些查询是什么,只是不知道用户选择了哪一个) 我允许用户从表中选择一组行并点击OK按钮,然后我想将这些行复制到新的DataGridView 我天真地使用了以下代码: DataGridView_New.DataSource = DataGridView_Old.SelectedRows 这使我在新DataGridView中的行数等于SelectedRows中的行数,但这些列不是SQL查询中的列(就像在Dat
DataGridView_New.DataSource = DataGridView_Old.SelectedRows
这使我在新DataGridView中的行数等于SelectedRows
中的行数,但这些列不是SQL查询中的列(就像在DataGridView_Old
中一样);相反,它们是每一行的行属性(DefaultCellStyle、Resizeable、ReadOnly等)
有没有简单快捷的方法从
DataGridView\u Old
获取列数据,并将所选行复制到DataGridView\u New
中?我不确定它是否适用于数据集,但您可以尝试使用每个所选行的属性填充新网格,例如:
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;
}
}
public void Populate()
{
var selectedRows=GetRows(DataGridView\u Old.selectedRows);
DataGridView\u New.DataSource=selectedRows
.Select(r=>r.DataBoundItem).ToList();
}
公共IEnumerable GetRows(DataGridViewSelectedRowCollection行)
{
foreach(DataGridViewRow行中的行)
{
收益返回行;
}
}
这里有一个简单的方法可以满足您的需要:
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);
}
谢谢,就这样了。我不得不将我的数据加载函数修改成一个兼容的形状,但我应该感谢您的解决方案启发我将数据表传送到我的第二个控件。