In this post i will describe how to add an identity column to an already existing data table which contains data.Suppose we are having a data table that is returned by executing some query,now instead of modifying the query we can add a new column to the data table and make it as identity column.Here is the code to do so.
SqlDataAdapter da=new SqlDataAdapter(cmd,conn);
Dataset ds=new Dataset();
da.Fill(ds);
DataTable dt = ds.Tables[0];
//Now we have Data Table
DataColumn dc = new DataColumn("ID");
dc.AutoIncrement = true;
dc.AutoIncrementSeed = 1;
dc.AutoIncrementStep = 1;
ddt.Columns.Add(dc);
dc.SetOrdinal(0);
//Set values for existing rows
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
dt.Rows(i).Item("ID") = i + 1;
}