Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset AutoIncrement in DataTable

Tags:

c#

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 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;

It just left with the counter it left off before Clear(). How can I reset the AutoIncrement in the DataTable?

like image 596
KMC Avatar asked May 12 '11 02:05

KMC


2 Answers

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

like image 115
biju Avatar answered Sep 28 '22 02:09

biju


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.

like image 30
PiotrB Avatar answered Sep 28 '22 01:09

PiotrB