【问题标题】:Copy column details from DataGridViewSelectedRowCollection从 DataGridViewSelectedRowCollection 复制列详细信息
【发布时间】:2011-06-16 10:42:15
【问题描述】:

我有一个 DataGridView,它绑定到由设计时未知的 SQL 查询返回的 DataSet(好吧,我知道查询是什么,我只是不知道用户选择了哪个)。

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

天真地,我使用的代码如下:

DataGridView_New.DataSource = DataGridView_Old.SelectedRows

这使我的新 DataGridView 中的行数等于 SelectedRows 中的行数,但这些列不是 SQL 查询中的列(就像它们在 DataGridView_Old 中一样);相反,它们是每一行的 Row 属性(DefaultCellStyle、Resizable、ReadOnly 等)。

有没有什么快速简便的方法可以简单地从DataGridView_Old 中获取列数据并将选定的行复制到DataGridView_New 中?

【问题讨论】:

    标签: .net winforms datagridview


    【解决方案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);
    }
    

    【讨论】:

    • 谢谢,整理好了。不得不将我的数据加载功能打造成兼容的形状,但我可能应该感谢您的解决方案启发我将该 DataTable 带到我的第二个控件。
    【解决方案2】:

    我不确定它是否适用于 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;
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-09
      • 2018-06-27
      • 2016-11-21
      相关资源
      最近更新 更多