Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

@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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top