How to add identity column to datatable using c#

前端 未结 6 1184
逝去的感伤
逝去的感伤 2020-12-16 18:37

How to add identity column to datatable using c#. Im using Sql compact server.

6条回答
  •  有刺的猬
    2020-12-16 19:33

    I dont think its a good idea to use autoincrement on datatable if you are using insert and delete to a datatable because the number will not be rearranget, no final i will share a small idea how can we use autoincrement manual.

             DataTable dt = new DataTable();
            dt.Columns.Add("ID",typeof(int));
            dt.Columns.Add("Produto Nome", typeof(string));  
    
            dt.Rows.Add(null, "A");
            dt.Rows.Add(null, "B");
            dt.Rows.Add(null, "C");
    
            for(int i=0;i < dt.Rows.Count;i++)
            {
                dt.Rows[i]["ID"] = i + 1;
            }
    

    always when finalizing the insert or delete must run this loop

             for(int i=0;i < dt.Rows.Count;i++)
            {
                dt.Rows[i]["ID"] = i + 1;
            }
    

提交回复
热议问题