将datagridview行移动到另一个datagridView [英] move datagridview Row to another datagridView
问题描述
对于此类问题,我已经回答了其他答案,到目前为止,还没有任何方法能很好地工作.
I've gone through the other answers for this kind of question, nothing has really worked well so far.
我有一个foreach
循环,该循环应将源datagridview
中的行添加到目标datagridview
中,然后从源中删除该行.
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.
无效的操作异常是:Row provided already belongs to a DataGridView control.
我也无法使...Rows.Copy()
正常工作.有什么想法吗?
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);
}
推荐答案
您需要先将fromDataGridView
中的行删除,然后再将其添加到toDataGridView
.
You need to remove the row from fromDataGridView
before you add it to toDataGridView
.
但是您正在修改foreach
循环内的集合-无法使用.
But you're modifying the collection inside the foreach
loop - that won't work.
解决方法是复制要在foreach
中使用的集合.
The workaround is to copy the collection for use in the foreach
.
尝试一下:
foreach (DataGridViewRow selRow in fromDataGridView.SelectedRows.OfType<DataGridViewRow>().ToArray())
{
fromDataGridView.Rows.Remove(selRow);
toDataGridView.Rows.Add(selRow);
}
这篇关于将datagridview行移动到另一个datagridView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!