将DataGridView的行复制到另一个DataGridView中

VAS*_*hhh 7 c# clone datagridview

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

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

DataGridViewRowCollection tmpRowCollection = DataGridView1.Rows;

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

DataGridView2.Rows.AddRange((DataGridViewRow[]) tmpRowArray));
Run Code Online (Sandbox Code Playgroud)

但它一直这么说

"Row provided already belongs to a DataGridView control."
Run Code Online (Sandbox Code Playgroud)

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

小智 5

您可以通过以下链接使用该功能

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;
}
Run Code Online (Sandbox Code Playgroud)

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