Copy DataGridView's rows into another DataGrid

2019-02-17 16:33发布

So basically I've got 2 DataGridView and I need to copy the rows from one to the other.

So far I've tried:

DataGridViewRowCollection tmpRowCollection = DataGridView1.Rows;

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

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

But it keeps saying that

"Row provided already belongs to a DataGridView control."

So what's the best way to copy the content of the rows (both DataGridView have the same columns) ?

4条回答
混吃等死
2楼-- · 2019-02-17 17:04

I would recommend using a backing DTO for this. Instead of dealing with the rows directly, create a DTO that contains all the columns of your GridViews, then use a List of them as your DataSource. Then, all you have to do to add/remove rows is to add/remove DTOs in the list.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-02-17 17:23

you need to first clone the row from the original then add to new view. http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewrow.clone.aspx

查看更多
迷人小祖宗
4楼-- · 2019-02-17 17:27

You use the function at the following link

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

查看更多
倾城 Initia
5楼-- · 2019-02-17 17:31

just write this:

copyDGV.DataSource = mainDGV.DataSource;        
查看更多
登录 后发表回答