在已有数据后为 DataTable 设置自动编号 [英] Set autonumber for DataTable after it already has data
本文介绍了在已有数据后为 DataTable 设置自动编号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码将自动编号列添加到 DataTable
:
I have the following code to add an autonumber column to a DataTable
:
public void AddAutoIncrementColumn(DataTable dt)
{
DataColumn column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.AutoIncrement = true;
column.AutoIncrementSeed = 0;
column.AutoIncrementStep = 1;
dt.Columns.Add(column);
}
但是,对于表中已经存在的所有行,此值将为空;似乎只有在添加此列后添加的新行才会触发 AutoIncrement.有没有办法为已经存在的行设置自动编号值?
However, this value will be blank for all rows that are already in the table; it seems that the AutoIncrement is only triggered for new rows that are added after this column has been added. Is there a way to set autonumber values for the rows that already exist?
推荐答案
我认为当行已经在表中时不可能触发 AutoIncrement
功能.但是您可以轻松地手动更新表格:
I don't think that it's possible to trigger the AutoIncrement
functionality when the rows are already in the table. But you could update the table manually easily:
public void AddAutoIncrementColumn(DataTable dt)
{
DataColumn column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.AutoIncrement = true;
column.AutoIncrementSeed = 0;
column.AutoIncrementStep = 1;
dt.Columns.Add(column);
int index = -1;
foreach (DataRow row in dt.Rows)
{
row.SetField(column, ++index);
}
}
这篇关于在已有数据后为 DataTable 设置自动编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文