The best way to add a new sequentially numbered column to an existing data table

I have a non empty datatable. What is the best way to add another column to it that has sequential numbering starting at 1.

I tried the following code. But does not work.

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

Will there be an expression help setting in this scenario?

Thanks at Advance

+3
source share
3 answers

I think you could achieve this using the second data table "helper", which will only contain a field with auto-increment, and then you fill / merge it with 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();

dtIncremented dt. , .

+5

        // 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++;
            }
        }
    }
+1

You will need to create a completely new datatable for this and manually deeply copy each row from one of the old tables to the new. Unfortunately.

0
source

Source: https://habr.com/ru/post/1777596/


All Articles