Forums - C# Corner

Forum guidelines
Jennifer ODonovan

Jennifer ODonovan

  • 1.8k
  • 29
  • 4.4k

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;
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());
catch (Exception ex)
// SetSession();
//  Get the ID of the inserted record in the database

Answers (5)