Add Identity Column to a Data Table Containing Data

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.

  1. SqlDataAdapter da=new SqlDataAdapter(cmd,conn);  
  2. Dataset ds=new Dataset();  
  3. da.Fill(ds);  
  4. DataTable dt = ds.Tables[0];  
  5. //Now we have Data Table  
  6. DataColumn dc = new DataColumn("ID");  
  7. dc.AutoIncrement = true;  
  8. dc.AutoIncrementSeed = 1;  
  9. dc.AutoIncrementStep = 1;  
  10. ddt.Columns.Add(dc);  
  11. dc.SetOrdinal(0);  
  12.   
  13. //Set values for existing rows  
  14. for (int i = 0; i <= dt.Rows.Count - 1; i++)  
  15. {  
  16.    dt.Rows(i).Item("ID") = i + 1;  
  17. }