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

前端 未结 3 1948
囚心锁ツ
囚心锁ツ 2021-02-11 02:03

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

I tried the following code. But did not wo

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-11 02:11

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

提交回复
热议问题