【问题标题】:Reset AutoIncrement in DataTable在 DataTable 中重置 AutoIncrement
【发布时间】:2011-05-12 02:26:20
【问题描述】:

我用DataAdapterDataSet 填充到SQL CE 数据库。数据显示在绑定到 DataSet 的 DataTable 的 DataGrid 上。我的数据源中有一个自动增量 ID 字段(或在 SQLCE 中,称为 PRIMARY KEY IDENTITY);相应地,我还在我的DataTable 中设置了一个 AutoIncrement ID 列。

/* when DataTable is first populated, start counting from Rows.Count */
/* if empty, starts with 1 */
dt.Column["id"].AutoIncrementSeed = dt.Rows.Count + 1;

当我清除我的 DataTable 时出现问题。我想将 AutoIncrement Counter 重置回 1 但无法,我尝试了以下操作:

/* clearing and disposing DataTable, DataSet, DataAdaptor does not reset the counter */
dt.Clear();
dt.Dispose();
ds.Clear();
ds.Dispose()
da.Dispose()

/* manually re-setting the AutoIncrementSeed also does not reset the counter */
dt.Column["id"].AutoIncrementSeed = 1;

它刚刚离开了在Clear() 之前离开的计数器。如何重置 DataTable 中的 AutoIncrement?

【问题讨论】:

    标签: c# datatable


    【解决方案1】:

    这样使用

    dt.Clear();
    dt.Column["id"].AutoIncrementStep = -1;
    dt.Column["id"].AutoIncrementSeed = -1;
    
    dt.Column["id"].AutoIncrementStep = 1;
    dt.Column["id"].AutoIncrementSeed = 1;
    

    查看以下链接了解更多

    http://www.eggheadcafe.com/community/aspnet/10/25407/autoincrementseed.aspx

    【讨论】:

      【解决方案2】:

      我已将代码简化为这个版本:

      dt.Column["id"].AutoIncrement = True
      dt.Column["id"].AutoIncrementSeed = 0
      dt.Column["id"].AutoIncrementStep = -1
      dt.Column["id"].AutoIncrementSeed = -1
      

      这对我来说更好,因为种子和步骤的值为 -1。 我认为 AutoIncrementSeed 属性的实现是这样的:

      if (_AutoIncrementSeed <> value)
          _InternalAutoIncrementSeed = value 
      _AutoIncrementSeed = value
      

      而 _InternalAutoIncrementSeed 用于 NewRow 函数。

      【讨论】:

        猜你喜欢
        • 2010-10-05
        • 1970-01-01
        • 2012-07-09
        • 2023-04-09
        • 1970-01-01
        • 2019-09-21
        • 1970-01-01
        • 2010-10-16
        相关资源
        最近更新 更多