简体   繁体   English

无法将数据列从一个数据表复制到另一数据表

[英]Unable to Copy datacolumn from one data table to another

How can I copy 1 data column from 1 data table to a new datatable. 如何将1个数据列从1个数据表复制到新数据表。 When I try to do it, I get the error Column 'XXX' already belongs to another DataTable.? 当我尝试执行此操作时,出现错误列'XXX'已经属于另一个DataTable。

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

Thanks in Advance 提前致谢

You cannot copy DataColumns. 您不能复制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. 您需要做的是在新数据表中创建一个新数据列,其数据类型与旧数据表的列中的数据类型相同,然后您需要运行一个FOR循环,以将所有数据从旧数据表引入到新数据表中数据表。

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"];
}

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. 另外,如果要复制的数据是引用类型,而不是值类型,则可能需要查看.Clone()方法是否适用于该类型,或者自己创建一个。 Just doing 'this = that' in the FOR loop will not work on reference types. 仅在FOR循环中执行“ this = that”将不适用于引用类型。

You cannot copy a DataColumn. 您不能复制DataColumn。 (DataColumns are very tightly coupled with their tables) (DataColumn与表紧密耦合)

Instead, you can add a new column with the same name and datatype. 相反,您可以添加具有相同名称和数据类型的新列。

You might be looking for DataTable.Clone() , which will create a structual copy of an entire table. 您可能正在寻找DataTable.Clone() ,它将创建整个表的结构副本。 (With the same schema, but no data) (具有相同的架构,但没有数据)

Just a thought, are your DataTables both in the same DataSet? 只是想一想,您的DataTables是否都在同一个DataSet中?

If so, you can create a named DataRelation between the columns of two tables (think foreign key). 如果是这样,您可以在两个表的列之间创建一个命名的DataRelation (请考虑外键)。

Then you can add a Calculated DataColumn to your table that has its Expression property set to "Child(RelationName).ColumnName" or "Parent(RelationName).ColumnName" depending on the direction of the relationship. 然后,可以将Calculated DataColumn添加到表中,该表达式的Expression属性设置为“ Child(RelationName).ColumnName”或“ Parent(RelationName).ColumnName”,具体取决于关系的方向。

This will give you the same effect as copying the column, but I believe it only evaluates it lazily. 这将为您提供与复制列相同的效果,但我相信它只会对它进行惰性计算。 So maybe it will give you what you need. 因此,也许它将为您提供所需的东西。

There is an example here of how this works. 有一个例子在这里是如何工作的。 The example uses the Sum aggregate function, but you just need to reference the column name and it will duplicate it in your DataTable 该示例使用Sum聚合函数,但是您只需要引用列名,它将在您的DataTable中复制它

myDataSet.Relations.Add(
    "Orders2OrderLines", 
    myDataSet.Tables["Orders"].Columns["OrderID"], 
    myDataSet.Tables["OrderLines"].Columns["OrderID"]);

ordersTable.Columns.Add("OrderTotal", typeof(decimal), "Sum(Child(Orders2OrderLines).ExtendedPrice)");

HTH 高温超导

The problem is caused by the c# can not reuse the object instance created and uses it on multiples DataTables. 该问题是由于c#无法重用创建的对象实例并在多个DataTables上使用它而引起的。 For this it is necessary to create a new object DataCollumn for each loop iteration. 为此,有必要为每个循环迭代创建一个新的对象DataCollumn。

foreach (DataTable table in DATASET.Tables)
{
    DataColumn yourDataCollumn = new DataColumn("Name of DataCollumn", typeof(Your data type));
    // your logic here
}

Hope it's help... 希望对您有帮助...

I used the below to merge two tables using mostly LINQ and only looping through the rows at the end. 我使用以下内容主要使用LINQ合并了两个表,并且只循环了最后的行。 I wouldn't call it pretty but it does work. 我不会称它为漂亮,但确实可以。 Using the join to prevent some of the assumptions listed above. 使用联接来防止上面列出的某些假设。

DataTable tableOne = getTableOne();
DataTable tableTwo = getTableTwo();

var oneColumns = tableOne.Columns.Cast<DataColumn>()
                                 .Select(p => new Column(p.ColumnName, DataType))
                                 .ToArray();

var twoColumns = tableTwo.Columns.Cast<DataColumn>()
                                 .Select(p => new DataColumn(p.ColumnName, p.DataType))
                                 .ToArray();


var matches = (from a in tableOne.AsEnumerable()
               join b in tableTwo.AsEnumerable() on a["column_name"] equals b["column_name"]
               select a.ItemArray.Concat(b.ItemArray)).ToArray();


DataTable merged = new DataTable();
merged.Columns.AddRange(oneColumns);
merged.Columns.AddRange(twoColumns);

foreach (var m in matches) { merged.Rows.Add(m.ToArray()); }

No looping required , Refer this , Hope this should solve your problem... 无需循环,请参阅,希望这可以解决您的问题...

DataTable dt = new DataTable(); 
//fill the dt here 
DataTable dt2 = new DataTable(); 
string[] strCols = {"Column Name to copy"}; 
dt2 = dt.DefaultView.ToTable("newTableName", false, strCols);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM