views:

3002

answers:

3

I'm just getting dirty in WinForms, and I've discovered, through a lovely tutorial, the magic of dragging a database table onto the design view of my main form. So, all is lovely, I've got my DataGridView with all of the columns represented beautifully.

BUT...

When I run my application against this brand new, empty .sdf (empty save for the two tables I've created, which are themselves empty), I get a -1 in the column corresponding to my primary key/identity column whenever I try to create that first record.

Any idea why this might be happening? If it helps, the column is an int.

+1  A: 

Since it is an Identity column and you haven't saved it to the database yet it is -1. I am assuming here that this is before you save the table back to the database, correct? You need to perform the insert before that value will be set correctly.

Craig
A: 

Thanks, Craig. That did the trick. Any idea why it shows a -1 instead of something that doesn't raise so much alarm? :-)

Brian Warshaw
+3  A: 

@Brian -1 is a good choice for the default value since no "real" rows are likely to have identities less than zero. If it defaulted to 0 or 1 then there'd be a chance that it'd clash with an existing row, causing a primary key violation.

For applications that stay offline and create multiple rows before saving, a common practice is to continue counting backwards (-2, -3, -4) for each new row's identity. Then when they're saved, the server can replace them with the true "next" value from the table.

Matt Hamilton