Reputation: 773
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
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.
TableAdapter.Insert
, not TableAdapter.Update
@@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.EDIT: Please see this walk-through for what you're trying to accomplish.
Upvotes: 3