Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy DataGridView's rows into another DataGridView

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) ?

like image 761
VAShhh Avatar asked Jun 13 '11 20:06

VAShhh


People also ask

How do I copy rows in DataGridView?

Solution 1. You can use DataGridViewRow. Clone Method[^] which creates an exact copy of this row.

How do I move selected rows from one DataGridView to another DataGridView?

Transfer (Copy) Selected (Checked) rows from one DataGridView to another in Windows Forms Application using C# Once all the rows visited then get the DataTable from the dataGridView2 and merge both the DataTable and then populate using the updated DataTable to display the previous and transferred data in dataGridview2.

How do you copy a data grid?

You can copy data from a grid report or from a grid report displayed in a document. Press CTRL+C , and the data is copied to the clipboard. You can now paste it into another application, such as Notepad or Excel, as shown in the image below.


1 Answers

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

like image 55
Wicked Coder Avatar answered Sep 24 '22 15:09

Wicked Coder