So basically I've got 2 DataGridView
and I need to copy the rows from one to the other.
So far I've tried:
开发者_JAVA百科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) ?
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
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
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.
just write this:
copyDGV.DataSource = mainDGV.DataSource;
精彩评论