Get the last inserted return id from the insert / update request

I want the last inserted id to be returned when pasted into 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: "The reference to the object is not installed in the instance of the object."

I set the tblClipManagerTableAdable.InsertQuery runtime for the scalar.

Any help on returning the last inserted id with my current code and setting?

Using a local SQL database (dbClipManager.sdf).

Best wishes


EDIT

I think I found what I could use.

But I am very new to this. Not sure how to fill in the code? I used only to use datasets, and not to open connections, execute SQL commands .: O /

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

Best wishes

+4
source share
1 answer

There are several problems with your approach, so I would advise you to quickly read the table adapter and make sure you have the basics .

  • If you are trying to add a new record, you should call TableAdapter.Insert , not TableAdapter.Update
  • You cannot create a second command in the database and use @@IDENTITY to return the ID that was previously generated ... this should be returned in the same session, otherwise SQL would not know what ID you expect to receive.
  • If you set the table adapter execution mode to scalar, then the identifier will be the return value of the method call. Please review this question and answer for the same issue as you.

EDIT: Please check out this walkthrough for what you are trying to accomplish.

+4
source

Source: https://habr.com/ru/post/1403508/


All Articles