Jennifer ODonovan

Jennifer ODonovan

  • NA
  • 29
  • 10.9k

Get the id of the inserted record in sql server database

Feb 27 2018 12:16 PM
I am looking to know how to Store a newly created ID(record) in sql server DB into a Session Variable. ( or other option)
 
For example:
I am using asp.Net Web Forms with a sql server Database
i have a web page where users enter in details of a booking and then click a addBooking button which stores this to my DB.
 
I am looking to know how to capture this Newly created ID to display it after that button is submitted 
 
protected void AddBooking_Click(object sender, EventArgs e)
{
//Creating a connection to my database using the connection string
string cs = ConfigurationManager.ConnectionStrings["BookingDb"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
//preparing a query which will insert the data entered in the textboxes to the database
SqlCommand cmd = new SqlCommand("[dbo].[spAddBooking]", con);
cmd.CommandType = CommandType.StoredProcedure;
try
{
cmd.Parameters.AddWithValue("@UserId", UserID.Text.Trim());
cmd.Parameters.AddWithValue("@MemberType", ddlMemberType.SelectedValue);
cmd.Parameters.AddWithValue("@PitchSection", ddlSyntheticPitch.SelectedValue);
cmd.Parameters.AddWithValue("@Date", txtDate.Text.Trim());
cmd.Parameters.AddWithValue("@StartTime", ddlStartTime.SelectedValue);
cmd.Parameters.AddWithValue("@EndTime", ddlEndTime.SelectedValue);
cmd.Parameters.AddWithValue("@Description", txtDescription.InnerText.Trim());
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex);
}
finally
{
// SetSession();
con.Close();
Response.Redirect("WebForm2.aspx");
}
}
 
//  Get the ID of the inserted record in the database
 

Answers (6)