将datagridview行移动到另一个datagridView [英] move datagridview Row to another datagridView

查看:265
本文介绍了将datagridview行移动到另一个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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆