Reputation: 981
I've built a form for entering some data into a table in my database, now I want to INSERT that data, and get back the ID (which is an autonumber) of the record that has just been added. I've got the INSERT part working just fine, and I've tacked "SELECT SCOPE_IDENTITY();" onto the end of that, but now I need to retrieve the returned number.
At the moment all of this is done with an SqlDataSource (with the "INSERT" statement being put together and fired by some C# in the codebehind file, which takes data from a form on the page).
Is there a quick way to grab that number and put it in a variable?
Upvotes: 1
Views: 3537
Reputation: 189
SQLDataSource uses ExecuteNonQuery internally which means that you can't retrieve the value directly. A workaround is to pass an output parameter to your SqlataSource's insert parameters list, and then set the value returned by SCOPE_IDENTITY in that variable. The value of the variable can be retrieved from in the Inserted event.
That is,
Now the value of the @Identity parameter can be retrieved in the "Inserted" event as follows:
protected void SqlDataSource1_Inserted(object sender, SqlDataSourceStatusEventArgs e) {
//Read the value of the @Identity OUTPUT parameter int lastID = e.Command.Parameters["@Identity"].Value; ...
}
Upvotes: 2
Reputation: 69372
I believe this code might help:
protected void SqlDataSource1_Inserted(object sender, SqlDataSourceStatusEventArgs e)
{
//Read the value of the @Identity OUTPUT parameter
string sID = e.Command.Parameters["@Identity"].Value.ToString();
//Display new ID
Label1.Text = sID;
}
That was from this blog post
Upvotes: 1