无法从一个数据表中复制的DataColumn到另一个 [英] Unable to Copy datacolumn from one data table to another

查看:691
本文介绍了无法从一个数据表中复制的DataColumn到另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何可以复制从1数据表1中的数据列到一个新的数据表。当我尝试这样做,我得到的错误列'XXX'已属于另一个数据表?

How can I copy 1 data column from 1 data table to a new datatable. When I try to do it, I get the error Column 'XXX' already belongs to another DataTable.?

dataColumn = datatable1.Columns[1];
datatable2 = new DataTable();
datatable2.Columns.Add(dataColumn);

在此先感谢

推荐答案

您不能复制DataColumns。什么,你需要做的就是创建新的数据表具有相同的数据类型在老的数据表的列一个新的DataColumn,然后你需要运行一个FOR循环中的所有数据从旧的数据表带来新的数据表。

You cannot copy DataColumns. What you'll need to do is create a new DataColumn in the new datatable with the same data type as in the old datatable's column, and then you need to run a FOR loop to bring in all the data from the old datatable to the new datatable.

请参阅下面的code。这假定该数据表具有行完全相同的编号。

See the following code. This assumes that the datatables have exactly the same number of rows.


DataTable dt1 = new DataTable();
DataTable dt2 = new DataTable();

dt2.Columns.Add("ColumnA", dt1.Columns["ColumnA"].DataType);

for (int i = 0; i < dt1.Rows.Count; i++)
{
    dt2.Rows[i]["ColumnA"] = dt1.Rows[i]["ColumnA"];
}

此外,如果您要复制的数据是引用类型而不是值类型,你可能想看看是否.Clone()方法可用于类型,或做一个自己。只是做'这个=,在FOR循环将无法在引用类型的工作。

Also, If the data you are copying are reference types and not value types you might want to see if a .Clone() method is available for the type, or make one yourself. Just doing 'this = that' in the FOR loop will not work on reference types.

这篇关于无法从一个数据表中复制的DataColumn到另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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