Copy DataTable from one DataSet to another(将 DataTable 从一个 DataSet 复制到另一个)
问题描述
我正在尝试向新数据集 X 添加一个位于不同数据集 Y 内的数据表.如果我直接添加它,我会收到以下错误:
I'm trying to add to a new DataSet X a DataTable that is inside of a different DataSet Y. If I add it directly, I get the following error:
DataTable 已经属于另一个 DataSet.
我是否必须克隆 DataTable 并将所有行导入到其中,然后将新的 DataTable 添加到新的 DataSet 中?有更好/更简单的方法吗?
Do I have to clone the DataTable and import all the rows to it and then add the new DataTable to the new DataSet? Is there a better/easy way to do it?
推荐答案
有两种简单的方法可以做到这一点:
There are two easy ways to do this:
而不是 DataTable.Clone,使用 DataTable.Copy 创建数据表的副本;然后将副本插入到目标 DataSet:
Instead of DataTable.Clone, use DataTable.Copy to create a copy of your data table; then insert the copy into the target DataSet:
dataSetX.Tables.Add( dataTableFromDataSetY.Copy() );
DataSet.Merge
您也可以使用 DataSet.Merge 为此:
dataSetX.Merge(dataTableFromDataSetY);
但请注意,如果您要使用此方法,您可能需要确保您的目标 DataSet 尚未包含同名的表:
Note, however, that if you are going to use this method, you might want to make sure that your target DataSet doesn't already contain a table with the same name:
如果目标数据集不包含同名表,则在数据集中创建表的新副本;
If the target DataSet doesn't contain a table by the same name, a fresh copy of the table is created inside the data set;
如果同名表已经在目标数据集中,那么它将与传递给 Merge 的表合并,最终得到两者的混合.
If a table by the same name is already in the target data set, then it will get merged with the one passed to Merge, and you end up with a mix of the two.
这篇关于将 DataTable 从一个 DataSet 复制到另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将 DataTable 从一个 DataSet 复制到另一个
基础教程推荐
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
