将 datagridview 行移动到另一个 datagridView
我已经浏览了此类问题的其他答案,到目前为止没有什么真正有效的。
我有一个 foreach 循环,该循环应将源 datagridview 中的行添加到目标 datagridview 中,然后从源中删除该行。
无效操作异常是:提供的行已经属于 DataGridView 控件。
我也无法让 ...Rows.Copy()
工作。有什么想法吗?
foreach (DataGridViewRow selRow in fromDataGridView.SelectedRows)
{
toDataGridView.Rows.Add(selRow);
fromDataGridView.Rows.Remove(selRow);
}
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要先从
fromDataGridView
中删除该行,然后再将其添加到toDataGridView
中。但是您正在
foreach
循环内修改集合 - 这是行不通的。解决方法是复制该集合以在
foreach
中使用。试试这个:
You need to remove the row from
fromDataGridView
before you add it totoDataGridView
.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:
这是您可以执行或尝试的示例。
当删除一行时,行数也会减少,因此如果您将代码放入 for 循环并反向运行它,它会正常工作,看看:
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:
当存在
BindingSource
时,无法直接向DataGridView
添加新行。您应该将行添加到第二个视图的
BindingSource
中,并让它将该行添加到其网格中。我已经在工作解决方案中测试了以下代码。
Adding a new row directly to
DataGridView
is not possible when there isBindingSource
.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.