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) ?
Solution 1. You can use DataGridViewRow. Clone Method[^] which creates an exact copy of this row.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With