【问题标题】:Copy DataGridView's rows into another DataGridView将 DataGridView 的行复制到另一个 DataGridView
【发布时间】:2011-09-14 05:47:07
【问题描述】:

所以基本上我有 2 个DataGridView,我需要将行从一个复制到另一个。

到目前为止我已经尝试过:

DataGridViewRowCollection tmpRowCollection = DataGridView1.Rows;

DataGridViewRow[] tmpRowArray = new DataGridViewRow[tmpRowCollection.Count];
tmpRowCollection.CopyTo(tmpRowArray, 0);            

DataGridView2.Rows.AddRange((DataGridViewRow[]) tmpRowArray));

但它一直在说

"Row provided already belongs to a DataGridView control."

那么复制行内容的最佳方法是什么(DataGridView 具有相同的列)?

【问题讨论】:

    标签: c# datagridview clone


    【解决方案1】:

    您使用以下链接的功能

    private DataGridView CopyDataGridView(DataGridView dgv_org)
    {
        DataGridView dgv_copy = new DataGridView();
        try
        {
            if (dgv_copy.Columns.Count == 0)
            {
                foreach (DataGridViewColumn dgvc in dgv_org.Columns)
                {
                    dgv_copy.Columns.Add(dgvc.Clone() as DataGridViewColumn);
                }
            }
    
            DataGridViewRow row = new DataGridViewRow();
    
            for (int i = 0; i < dgv_org.Rows.Count; i++)
            {
                row = (DataGridViewRow)dgv_org.Rows[i].Clone();
                int intColIndex = 0;
                foreach (DataGridViewCell cell in dgv_org.Rows[i].Cells)
                {
                    row.Cells[intColIndex].Value = cell.Value;
                    intColIndex++;
                }
                dgv_copy.Rows.Add(row);
            }
            dgv_copy.AllowUserToAddRows = false;
            dgv_copy.Refresh();
    
        }
        catch (Exception ex)
        {
            cf.ShowExceptionErrorMsg("Copy DataGridViw", ex);
        }
        return dgv_copy;
    }
    

    http://canlu.blogspot.com/2009/06/copying-datagridviewrow-to-another.html

    【讨论】:

    • 谢谢,但我怀疑这是复制这些行的最快方法。我正在搜索是否可以在没有循环的情况下执行此操作。
    • 我会接受这个,因为它似乎是获得我需要的唯一方法。
    • 谢谢。我添加了这个(稍作修改)作为 DataGridViews 的扩展方法。
    【解决方案2】:

    您需要先从原始行克隆,然后添加到新视图。 http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewrow.clone.aspx

    【讨论】:

    • 如果我这样做 DataGridView2.Rows.AddRange((DataGridViewRow[]) tmpRowArray.clone())); 我会得到同样的错误。我是否必须在循环中克隆每一行? :|
    • 不幸的是,我认为是这样。但是,如果原始 datagridview 绑定到数据集,您可以将第二个 datagridview 绑定到数据集的相同或克隆,并获得您想要的。
    【解决方案3】:

    我建议为此使用支持 DTO。与其直接处理行,不如创建一个包含 GridView 的所有列的 DTO,然后使用它们的列表作为数据源。然后,添加/删除行所要做的就是在列表中添加/删除 DTO。

    【讨论】:

      【解决方案4】:

      就这样写吧:

      copyDGV.DataSource = mainDGV.DataSource;        
      

      【讨论】:

      • 欢迎来到 Stackoverflow。请正确格式化您的代码:) 最好的问候
      • @Dr.DEVELOPER:很好的尝试,虽然它对没有数据源的数据网格视图没有任何用处。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多