4

I have the following code to add an autonumber column to a DataTable:

public void AddAutoIncrementColumn(DataTable dt)
{
   DataColumn column = new DataColumn();
   column.DataType = System.Type.GetType("System.Int32");
   column.AutoIncrement = true;
   column.AutoIncrementSeed = 0;
   column.AutoIncrementStep = 1;
   dt.Columns.Add(column);
}

However, this value will be blank for all rows that are already in the table; it seems that the AutoIncrement is only triggered for new rows that are added after this column has been added. Is there a way to set autonumber values for the rows that already exist?

4

4 回答 4

9

我认为AutoIncrement当行已经在表中时,不可能触发该功能。但是您可以轻松地手动更新表格:

public void AddAutoIncrementColumn(DataTable dt)
{
    DataColumn column = new DataColumn();
    column.DataType = System.Type.GetType("System.Int32");
    column.AutoIncrement = true;
    column.AutoIncrementSeed = 0;
    column.AutoIncrementStep = 1;
    dt.Columns.Add(column);
    int index = -1;
    foreach (DataRow row in dt.Rows)
    {
        row.SetField(column, ++index);
    }
}
于 2013-04-23T21:55:02.867 回答
2

我对@Programnik 解决方案进行了更改。

DataTable dt = LoadDataTable();
using (DbDataReader dr = dt.CreateDataReader())
{
    //Get Original Datatable structure
    dt = dt.Clone();

    // Add Auto Increment Column called ID
    dt.Columns.Add(new DataColumn("ID")
    {
        AutoIncrement = true,
        AllowDBNull = false,
        AutoIncrementSeed = 1,
        AutoIncrementStep = 1,
        DataType = typeof(System.Int32),
        Unique = true
    });

    // Change Auto Increment Column Ordinal Position to 0 (ie First Column)
    dt.Columns["TabID"].SetOrdinal(0);

    // Re-load original Data
    dt.Load(dr);
}
于 2018-09-22T21:17:19.967 回答
1

我认为有一种更简单的方法不需要遍历所有行。Datatable 上有一个名为 CreateDataReader 的方法。因此,克隆您的原始数据表,添加标识列,从原始表创建数据读取器,然后使用数据读取器加载克隆的表。这将在标识列中生成数字,例如

// original data table
DataTable origDT;

// create a reader
DataReader dr = origDT.CreatDataReader();

//clone original
DataTable clonedDT  = origDT.Clone();

//add identity column
clonedDT.Columns.Add(new DataColumn(){AutoIncrement=true});

//load clone from reader, identity col will auto-populate with values
clonedDT.Load(dr);
于 2018-06-27T05:25:27.280 回答
0

这对我有用,我试图从另一个表中获取唯一值并让它们有一个新的 ID。

        DataTable FinalNest = new DataTable();
        FinalNest.Columns.Add(new DataColumn("CuttingPlan", typeof(int)) { AutoIncrement = true, AutoIncrementSeed = 1, AutoIncrementStep = 1 });
        FinalNest.Columns.Add("Material", typeof(string));
        FinalNest.Columns.Add("IncludedPartIDs", typeof(string));
        DataTableReader dr = cutPlan.DefaultView.ToTable(true, "Material", "IncludedPartIDs").CreateDataReader();
        FinalNest.Load(dr);
于 2021-12-30T21:36:32.230 回答