Reset AutoIncrement in DataTable
I populate a DataSet
with a DataAdapter
to a SQL CE Database. Data is displayed on a DataGrid
which is binded to DataSet's DataTable. I have an auto-increment ID field (or in SQLCE, called PRIMARY KEY IDENTITY
) in my DataSource; correspondingly, I also set a AutoIncrement ID column in my DataTable
.
/* when DataTable is first populated, start counting from Rows.Count */
/* if empty, starts with 1 */
dt.Column["id"].AutoIncrementSeed = dt.Rows.Count + 1;
Problem come when I clear my DataTable. I want to reset the AutoIncrement Counter back to 1 but not able to, I tried the following:
/* clearing and disposi开发者_开发百科ng 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;
It just left with the counter it left off before Clear()
. How can I reset the AutoIncrement in the DataTable?
Use like this
dt.Clear();
dt.Column["id"].AutoIncrementStep = -1;
dt.Column["id"].AutoIncrementSeed = -1;
dt.Column["id"].AutoIncrementStep = 1;
dt.Column["id"].AutoIncrementSeed = 1;
Check the below link for more
http://www.eggheadcafe.com/community/aspnet/10/25407/autoincrementseed.aspx
I've simplified code to this version:
dt.Column["id"].AutoIncrement = True
dt.Column["id"].AutoIncrementSeed = 0
dt.Column["id"].AutoIncrementStep = -1
dt.Column["id"].AutoIncrementSeed = -1
It's better for me, because of -1 values of seed and step. I think that implementation of AutoIncrementSeed property is like that:
if (_AutoIncrementSeed <> value)
_InternalAutoIncrementSeed = value
_AutoIncrementSeed = value
and _InternalAutoIncrementSeed is used in NewRow function.
精彩评论