将 DataGridView 的行复制到另一个 DataGridView
所以基本上我有 2 个 DataGridView,我需要将行从一个复制到另一个。
到目前为止我已经尝试过:
DataGridViewRowCollection tmpRowCollection = DataGridView1.Rows;
DataGridViewRow[] tmpRowArray = new DataGridViewRow[tmpRowCollection.Count];
tmpRowCollection.CopyTo(tmpRowArray, 0);
DataGridView2.Rows.AddRange((DataGridViewRow[]) tmpRowArray));
但它一直说
"Row provided already belongs to a DataGridView control."
那么复制行内容的最佳方法是什么(两个 DataGridView
都有相同的列)?
So basically I've got 2 DataGridView
and I need to copy the rows from one to the other.
So far I've tried:
DataGridViewRowCollection tmpRowCollection = DataGridView1.Rows;
DataGridViewRow[] tmpRowArray = new DataGridViewRow[tmpRowCollection.Count];
tmpRowCollection.CopyTo(tmpRowArray, 0);
DataGridView2.Rows.AddRange((DataGridViewRow[]) tmpRowArray));
But it keeps saying that
"Row provided already belongs to a DataGridView control."
So what's the best way to copy the content of the rows (both DataGridView
have the same columns) ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以通过以下链接使用该函数
http://canlu.blogspot .com/2009/06/copying-datagridviewrow-to-another.html
You use the function at the following link
http://canlu.blogspot.com/2009/06/copying-datagridviewrow-to-another.html
您需要首先从原始视图克隆行,然后添加到新视图。
http://msdn.microsoft.com/en -us/library/system.windows.forms.datagridviewrow.clone.aspx
you need to first clone the row from the original then add to new view.
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewrow.clone.aspx
我建议为此使用支持 DTO。不要直接处理行,而是创建一个包含 GridView 的所有列的 DTO,然后使用它们的列表作为数据源。然后,添加/删除行所需要做的就是在列表中添加/删除 DTO。
I would recommend using a backing DTO for this. Instead of dealing with the rows directly, create a DTO that contains all the columns of your GridViews, then use a List of them as your DataSource. Then, all you have to do to add/remove rows is to add/remove DTOs in the list.
就这样写:
just write this: