move datagridview Row to another datagridView

一世执手 提交于 2019-12-07 20:58:42

问题


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);
}

回答1:


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);
}



回答2:


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);     
}



回答3:


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]);
}


来源:https://stackoverflow.com/questions/9265165/move-datagridview-row-to-another-datagridview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!