C# 将数据列添加到数据表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11563731/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 18:20:20  来源:igfitidea点击:

Adding DataColumn to DataTable

c#datatable

提问by escobar_season

I want to move the data from a dataColumnto a specific column in my dataTable. I am not sure how to specify what column within my DatatableI want to add the datacolumn.

我想将数据从 a 移动dataColumn到我的dataTable. 我不确定如何指定Datatable我要添加的datacolumn.

        foreach (DataColumn col in dt.Columns)
        {
            dt1.Columns.Add(col);
        }

I receive an exception Column 'X' already belongs to another DataTable.

我收到一个例外 Column 'X' already belongs to another DataTable.

采纳答案by Tim Schmelter

You need to copy the properties like ColumnNameand create new DataColumns:

您需要复制类似的属性ColumnName并创建新的DataColumns

foreach (DataColumn col in dt.Columns)
{
    dt1.Columns.Add(col.ColumnName, col.DataType);
}

There's a reason for the ArgumentExceptionwhen you add a DataColumnwhich already belongs to another DataTable. It would be very dangerous to allow that since a DataTableholds a referenceto their columns and every column holds a referenceto it's DataTable. If you would add a column to another table your code would blow sooner or later.

ArgumentException添加DataColumn已经属于另一个 DataTable的 a 是有原因的。允许这样做是非常危险的,因为 aDataTable持有对其列的引用,并且每一列都持有对其 DataTable的引用。如果您将一列添加到另一个表中,您的代码迟早会崩溃。

If you also want to copy the DataRowsinto the new table:

如果您还想将 复制DataRows到新表中:

foreach (DataRow row in t1.Rows)
{
    var r = t2.Rows.Add();
    foreach (DataColumn col in t2.Columns)
    {
        r[col.ColumnName] = row[col.ColumnName];
    }
}

回答by Tamir

this is a normal behavior, if you're adding the same column to more than one DataTable ArgumentException will be thrown.

这是一种正常行为,如果您将同一列添加到多个 DataTable ArgumentException 将被抛出。

see documentation here: http://msdn.microsoft.com/en-us/library/55b10992.aspx

请参阅此处的文档:http: //msdn.microsoft.com/en-us/library/55b10992.aspx

you can create a new column same as the one you already added to the original table and add it to the new table.

您可以创建一个与已添加到原始表中的新列相同的新列并将其添加到新表中。

回答by D Stanley

Table data is organized by row, then by column. You can't (that I know of) add a column of data in one shot. You will need to add the column definitionto the second table and add the data to it separately.

表数据按行组织,然后按列组织。您不能(据我所知)一次性添加一列数据。您需要将列定义添加到第二个表并单独向其中添加数据。

Since your original code looped through all columns, you may be better off copying the original datatable using DataTable.Copy()and deleting what you don'twant.

由于您的原始代码循环遍历所有列,因此最好使用DataTable.Copy()并删除您想要的内容来复制原始数据表。

回答by JamieSee

You cannot add a DataColumn from another table, because it already has an association with it's original table and a DataColumn is passed by reference to the Add method because it's an Object. You'll have to copy it. Here's one way you can do that:

您不能从另一个表添加 DataColumn,因为它已经与它的原始表有关联,并且 DataColumn 通过引用传递给 Add 方法,因为它是一个对象。你必须复制它。这是您可以做到的一种方法:

public static class DataColumnExtensions
{
    public static DataColumn CopyTo(this DataColumn column, DataTable table)
    {
        DataColumn newColumn = new DataColumn(column.ColumnName, column.DataType, column.Expression, column.ColumnMapping);
        newColumn.AllowDBNull = column.AllowDBNull;
        newColumn.AutoIncrement = column.AutoIncrement;
        newColumn.AutoIncrementSeed = column.AutoIncrementSeed;
        newColumn.AutoIncrementStep = column.AutoIncrementStep;
        newColumn.Caption = column.Caption;
        newColumn.DateTimeMode = column.DateTimeMode;
        newColumn.DefaultValue = column.DefaultValue;
        newColumn.MaxLength = column.MaxLength;
        newColumn.ReadOnly = column.ReadOnly;
        newColumn.Unique = column.Unique;

        table.Columns.Add(newColumn);

        return newColumn;
    }

    public static DataColumn CopyColumnTo(this DataTable sourceTable, string columnName, DataTable destinationTable)
    {
        if (sourceTable.Columns.Contains(columnName))
        {
            return sourceTable.Columns[columnName].CopyTo(destinationTable);
        }
        else
        {
            throw new ArgumentException("The specified column does not exist", "columnName");
        }
    }
}

public class MyClass
{
    public static void Main()
    {
        DataTable tableA = new DataTable("TableA");
        tableA.Columns.Add("Column1", typeof(int));
        tableA.Columns.Add("Column2", typeof(string));

        DataTable tableB = new DataTable("TableB");

        foreach (DataColumn column in tableA.Columns)
        {
            column.CopyTo(tableB);
        }
    }
}

Note that there is also an extension method that can be used to Copy individual columns by name, i.e. tableA.CopyColumnTo("Column1", tableB);.

请注意,还有一个扩展方法可用于按名称复制单个列,即tableA.CopyColumnTo("Column1", tableB);.

Then you can copy the data like this if the new table is an exact copy of the original:

如果新表是原始表的精确副本,则您可以像这样复制数据:

foreach (DataRow row in tableA.Rows)
{
    tableB.Rows.Add(row.ItemArray);
}

Or in a way similar to the second piece of code in Tim Schmelter's answer if it is not an exact copy. I would, however, recommend some error checking if you aren't copying all the columns into the new table:

或者以类似于 Tim Schmelter 答案中的第二段代码的方式,如果它不是一个精确的副本。但是,如果您没有将所有列复制到新表中,我会建议进行一些错误检查:

foreach (DataRow souceRow in sourceTable.Rows)
{
    DataRow destinationRow = destinationTable.Rows.Add();

    foreach (DataColumn destinationColumn in destinationTable.Columns)
    {
        string columnName = destinationColumn.ColumnName;

        if (sourceTable.Columns.Contains(columnName))
        {
            destinationRow[columnName] = sourceRow[columnName];
        }
    }
 }