最好的方法与添加顺序编号的新列在现有的数据表 [英] Best way add a new column with sequential numbering in an existing data table
问题描述
我有一个非空的数据表。这是另一列添加到它具有顺序编号从1开始的最佳方式。
I have a non empty datatable . What is the best way to add another column to it that has sequential numbering starting from 1.
我尝试以下code。但没有奏效。
I tried the following code. But did not work.
DataColumn dc = new DataColumn("Col1");
dc.AutoIncrement = true;
dc.AutoIncrementSeed = 1;
dc.AutoIncrementStep = 1;
dc.DataType = typeof(Int32);
dt.Columns.Add(dc);
将设置任何EX pression帮助在这种情况?
Will setting any expression help in this scenario ?
在此先感谢
推荐答案
我认为你可以做到这一点通过使用第二个帮手的数据表,该表将只包含一个自动递增字段,然后您填充/与它合并现有的数据,这样的事情:
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();
然后你只需返还原物DT的dtIncremented表代替。不是一个完美的解决方案,但应该工作。
And then you would just return dtIncremented table instead of the original dt. Not an elegant solution but should work.
这篇关于最好的方法与添加顺序编号的新列在现有的数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!