Reputation: 9546
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?
Upvotes: 5
Views: 17289
Reputation: 5832
I made a change to @Programnik solution.
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 (i.e. First Column)
dt.Columns["ID"].SetOrdinal(0);
//Re-load original Data
dt.Load(dr);
}
Upvotes: 2
Reputation: 57
This worked for me I was trying to get the unique values from another table and have them have a new 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);
Upvotes: 0
Reputation: 1555
I think there is an easier way which doesn't require looping through all the rows. There is a method on Datatable called CreateDataReader. So, clone your original datatable, add the identity column, create a datareader from the original table, then load the cloned table with the data reader. This will generate numbers in the identity column, eg
// 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);
Upvotes: 1
Reputation: 460158
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);
}
}
Upvotes: 11