Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Automatically Assigning a Primary Key to a New Record from C#

Status
Not open for further replies.

stillinlife101

Programmer
Feb 15, 2005
29
US
I have a form that was more or less automatically generated by C# Express 2005 by dragging the "details" view of a SQL table onto a form. I have a bunch of textboxes connected to a dataset and the corresponding toolbar.

I don't want the user to play around with the primary key, so I have the "ID" field set to read-only. How can I have that box automatically filled in so I don't get a "field cannot be null" when the user tries to save a new record?

Thanks,

Dan
 
if the primary key is auto incremented by the db. then you can't get an ID until you insert the record. this is by design.

you could guess at the next id by selecting the max id from the db and adding 1, but that still isn't accurate because someone else could save a record before the current user did.

if that happens then either the current user thinks it's the wrong id, or the system will crash with duplicate pk error. either way it's not good.

usually it's not a good idea to show the db pk to the user. if the must see an id, create a unique constraint index on the column they think is the pk. then let them see/modify this as much as they want. the UI will ensure they don't duplicate the value. this makes is easier to keep your system in check too. as now your db has a pk which links to other tables and the use gets a key they can maintain, or at least assume it's the pk.

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
Here's an idea - don't display the ID.

The other option would be to use a Guid rather than an incremental ID. You can set that yourself and insert it into the db and it's basically guaranteed to be unique.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top