SF Alba
SF Alba

Reputation: 1

Adding data to SQL tables in C#

This may or may not be a noob question, so I'm sure it should be solved easily enough.

I'm trying to use a table in a .mdf database for a contacts list programme I'm writing. For the ID for each of the entries I put, I've got an Identity seed of 1000, with in increment of 1. This works fine when I input things directly into the table. The first entry is 1000, the second is 1001 and so on. I put some text boxes onto the form, and dragged each data source from the table onto their respective text box, so that new entries can be added from the form. The first two entries, which I added directly into the table, show up fine on the form, with their ID as I've previously stated. It's when I try to add a new entry using the form and the controls that I've created that problems arise.

When I add a new entry, the Contact ID for the new entry is set to -1, then -2 and so on. Why is this happening, and how can I fix it?

Relevant snips:

First entry is in there and works fine

enter image description here

New entry has an ID of -1 for some reason

enter image description here

Upvotes: 0

Views: 95

Answers (2)

T.S.
T.S.

Reputation: 19394

Make ID field read-only or don't show it altogether. The INSERT sql for your form should not include identity, i.e.

Insert into contacts (name, company, telephone, mobile, email) 
Output INSERTED.*
Values (. . . .  .)

If you in c# do command.ExecuteReader using above sql, you will get back all values including ID

Upvotes: 0

McNets
McNets

Reputation: 10827

It is default value for IDENTITY fields.

As far as you cannot know which will be the value of an IDENTITY fields unless you insert the record, by default it show -1

The best way to avoid it, it now showing this field when you dateset is on INSERT mode.

In fact, if you try to set it value manually, you will get an error.

Upvotes: 1

Related Questions