Best way add a new column with sequential numbering in an existing data table

三世轮回 提交于 2019-12-03 09:39:22

I think you could achieve that by using a 2nd "helper" data table that would contain just an auto-increment field and then you populate/merge it with the existing data, something like this:

DataTable dtIncremented  = new DataTable(dt.TableName);
DataColumn dc            = new DataColumn("Col1");
dc.AutoIncrement         = true;
dc.AutoIncrementSeed     = 1;
dc.AutoIncrementStep     = 1;
dc.DataType              = typeof(Int32);    
dtIncremented.Columns.Add(dc);

dtIncremented.BeginLoadData();

DataTableReader dtReader = new DataTableReader(dt);
dtIncremented.Load(dtReader);

dtIncremented.EndLoadData();

And then you would just return dtIncremented table instead of the original dt. Not an elegant solution but should work.

below code worked for me

Code is Edited

        // Added temp rows so that this solution can mimic actual requirement

        DataTable dt = new DataTable();
        DataColumn dc1 = new DataColumn("Col");
        dt.Columns.Add(dc1);

        for(int i=0;i<10;i++)
        {
            DataRow dr = dt.NewRow();
             dr["Col"] = i.ToString();
             dt.Rows.Add(dr);
        }


        // Added new column with Autoincrement, 

        DataColumn dc = new DataColumn("Col1"); 
        dc.AutoIncrement = true;
        dc.AutoIncrementSeed = 1;
        dc.DataType = typeof(Int32);

        // Handeled CollectionChanged event

        dt.Columns.CollectionChanged += new CollectionChangeEventHandler(Columns_CollectionChanged);
        dt.Columns.Add(dc);

        // After column added demostratation

        DataRow dr1 = dt.NewRow();
            dt.Rows.Add(dr1);



    void Columns_CollectionChanged(object sender, CollectionChangeEventArgs e)
    {
        DataColumn dc = (e.Element as DataColumn);
        if (dc != null && dc.AutoIncrement)
        {
            long i = dc.AutoIncrementSeed;
            foreach (DataRow drow in dc.Table.Rows)
            {
                drow[dc] = i;
                i++;
            }
        }
    }

You'll have to build a whole new datatable for this and manually deep-copy each row one by one from the old table to the new. Sorry.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!