Reputation: 2321
I've gone through the other answers for this kind of question, nothing has really worked well so far.
I have a foreach
loop that should add the the row from the source datagridview
to the destination datagridview
then remove that row from the source.
The invalid operation exception is: Row provided already belongs to a DataGridView control.
I couldn't get ...Rows.Copy()
to work either. Any ideas?
foreach (DataGridViewRow selRow in fromDataGridView.SelectedRows)
{
toDataGridView.Rows.Add(selRow);
fromDataGridView.Rows.Remove(selRow);
}
Upvotes: 2
Views: 9951
Reputation: 3343
Adding a new row directly to DataGridView
is not possible when there is BindingSource
.
You should add row to the BindingSource
of second view and let it to add the row to its grid.
I've tested the below code in a working solution.
var selectedRows = dataGridView1.SelectedRows;
int count = dataGridView1.SelectedRows.Count;
for (int i = 0; i < count; i++)
{
bindingSource2.Add(bindingSource1[selectedRows[i].Index]);
dataGridView1.Rows.Remove(selectedRows[i]);
}
Upvotes: 0
Reputation: 2990
You need to remove the row from fromDataGridView
before you add it to toDataGridView
.
But you're modifying the collection inside the foreach
loop - that won't work.
The workaround is to copy the collection for use in the foreach
.
Try this:
foreach (DataGridViewRow selRow in fromDataGridView.SelectedRows.OfType<DataGridViewRow>().ToArray())
{
fromDataGridView.Rows.Remove(selRow);
toDataGridView.Rows.Add(selRow);
}
Upvotes: 4
Reputation: 18843
Here is an example of what you could do or try..
its happening when one row is removed the rows count decrements too so if you put your code in for loop and run it in reverse it would work fine have a look:
for (int selRow = dataGridView1.Rows.Count -1; selRow >= 0 ; selRow--)
{
toDataGridView.Rows.Add(selRow);
fromDataGridView.Rows.Remove(selRow);
}
Upvotes: 1