Unable to Copy datacolumn from one data table to another

后端 未结 6 883
独厮守ぢ
独厮守ぢ 2021-01-17 22:28

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.?



        
相关标签:
6条回答
  • 2021-01-17 23:00

    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.

    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. Just doing 'this = that' in the FOR loop will not work on reference types.

    0 讨论(0)
  • 2021-01-17 23:00

    I used the below to merge two tables using mostly LINQ and only looping through the rows at the end. 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()); }
    
    0 讨论(0)
  • 2021-01-17 23:05

    The problem is caused by the c# can not reuse the object instance created and uses it on multiples DataTables. For this it is necessary to create a new object DataCollumn for each loop iteration.

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

    Hope it's help...

    0 讨论(0)
  • 2021-01-17 23:11

    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);
    
    0 讨论(0)
  • 2021-01-17 23:22

    Just a thought, are your DataTables both in the same DataSet?

    If so, you can create a named DataRelation between the columns of two tables (think foreign key).

    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.

    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

    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

    0 讨论(0)
  • 2021-01-17 23:24

    You cannot copy a DataColumn. (DataColumns are very tightly coupled with their tables)

    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. (With the same schema, but no data)

    0 讨论(0)
提交回复
热议问题