user1281991
user1281991

Reputation: 773

Get last inserted ID return from a insert/update query

I want to get the last inserted id returned when inserting in my visual C# program.

// Insert to database
try
{

    int result = int.Parse(tblClipManagerTableAdapter.InsertQuery(textBox2.Text, textBox1.Text).ToString());
    MessageBox.Show(result.ToString());
}
catch (Exception ex) {
    MessageBox.Show("Fejl: " + ex.Message.ToString());
}

Error is: "Object reference not set to an instance of an object."

I have set the tblClipManagerTableAdapter.InsertQuery execute mode to scalar.

Any help on how to return the last inserted ID with my current code and setup?

Using a local SQL database (dbClipManager.sdf).

Best regards


EDIT

I think I found something that I could use.

But I am very new to this. Not sure how to complety write the code? Im used to just use the datasets, not opening connections, execute SQL cmds. :o/

http://social.msdn.microsoft.com/Forums/en-US/sqlce/thread/1d1d3267-dc29-470b-bb20-00487a39bc87/

Best regards

Upvotes: 4

Views: 3940

Answers (1)

Michael Fredrickson
Michael Fredrickson

Reputation: 37378

There are several problems with your approach, so I'd suggest you do a quick read through of table adapter and make sure that you've got the basics down.

  1. If you're trying to add a new record, you should be calling TableAdapter.Insert, not TableAdapter.Update
  2. You can't create a second command to the database and use @@IDENTITY to get back the ID that was previously generated... this has to be returned within the same session, otherwise SQL would have no idea which ID you are expecting to receive.
  3. If you set the execute mode of the table adapter to scalar, then the ID will be the return value of the method call. Please see this Question and Answer on the same issue that you're experiencing.

EDIT: Please see this walk-through for what you're trying to accomplish.

Upvotes: 3

Related Questions