Link to home
Start Free TrialLog in
Avatar of bobinorlando
bobinorlando

asked on

How to make DataTable.Columns("PrimaryKeyCol").AutoIncrement work with a SQL Server Primary Key field

I have a table in SQL server 2000 that I am displaying in a vb.net 1.1 VS 2003 windows forms datagrid.
I am using drag and drop connection and dataadapter objects and generating the dataset in the designer.
I am instantiating a commandbuilder in code to handle CRUD commands.
The Sql server table has a primary key col and has existing records.
The Sql server table primary key column is not set to be an Identity column.

I am not displaying the primary key column in the datagrid, but when I add a new row, I want the dataadapter to properly insert the new row.
Currently I have set the autoincrement properties as follows:
   DataTable.Columns("PrimaryKeyCol").AutoIncrementSeed = -1
   DataTable.Columns("PrimaryKeyCol").AutoIncrementStep = -1
   DataTable.Columns("PrimaryKeyCol").AutoIncrement = True

So far so good and I can add new records sucessfully.
Therefore, not surprisingly, the new records added via my app in sql server have primary key incrementing from  -1 step -1.
Instead of this, I want sql server to automatically assign the next highest primary key value.

I recall reading somewhere that I can set the Primary key col to Identity = Yes.
Doing this does indeed seem to work.
SQL server seems to ignore the values set in autoincrement in the app and correctly inserts its own id value.

My question is, exactly how are the dataadapter and sql server working under the covers to make this happen?

Thanks in advance.
Avatar of vbturbo
vbturbo
Flag of Denmark image



        Dim oDatarow As DataRow
        Dim Id As Integer


                 'set the " Columns(0) " to which contains a unique id in the datatable
                 Dim pk(0) As DataColumn
                 pk(0) = ds.Tables("Test").Columns("PrimaryKeyCol").
                ds.Tables("Test").PrimaryKey = pk

                ds.Tables("Test")..Rows.Find(Id) ' find the particular row with that primary key
                oDatarow.Delete()' e.g delete this row

btw

DataTable.Columns("PrimaryKeyCol").AutoIncrementStep = -1
has to be
DataTable.Columns("PrimaryKeyCol").AutoIncrementStep = +1

vbturbo
ASKER CERTIFIED SOLUTION
Avatar of Sancler
Sancler

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of bobinorlando
bobinorlando

ASKER

Guys thanks for taking a stab at this.
 

I found the source of the autoincrement = -1 idea.

Exploring the ADO.NET DataRow
http://msdn2.microsoft.com/en-us/magazine/cc164076.aspx