move datagridview Row to another datagridView

独自空忆成欢 提交于 2019-12-06 12:51:48
Roy Goode

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

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

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