设置自动编号为DataTable中它已经拥有数据后, [英] Set autonumber for DataTable after it already has data

查看:323
本文介绍了设置自动编号为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);
}



但是,此值将是空白对于那些已经在表中的所有行;似乎自动增量​​时,才会触发此列已经被添加之后添加新行。有没有办法为已经存在的行设置自动编号值?

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?

推荐答案

我不认为这有可能触发当行已经在表中的自动增加功能。但是,你可以手动地更新表:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆