Search code examples
c#datatable

Set autonumber for DataTable after it already has data


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?


Solution

  • I don't think that it's possible to trigger the AutoIncrement functionality when the rows are already in the table. But you could update the table manually easily:

    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);
        }
    }