• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 365
  • Last Modified:

Scope Identity: Retrieve Record ID after Insert

I have a form that inserts into a database table succesfully.  After the insert, I want to display some information about the newly inserted record on a results page.  I thought about query string, session etc.  

I already retrieve the cope identity in the procedure.

I am working in c#.
1 Solution
Either a querystring or a session variable would work fine.  If using a querystring, the user can see the content which is okay as long as you feel this is not a security issue.  Once the data is saved, then simply response.redirect("yourresultpage.aspx?id=" + _scope_identity_id_from_db).  The only problem with a session variable is that if the page is refreshed after the server timeout period, then the id held in the session disappears and your code would fail.  As the querystring retains all the data it needs, timeout might not be such an issue (although if your code uses other time-dependant variables then yoou have the same issue).  The benefit of the session over the response.redirect method is that you can use server.transfer after you store the id of the record in the session, saving a round-trip to the server.

Moving on... in the "yourresultpage.aspx" - the attached code snippet opens the database, the command object and the datareader to display the record.

I hope I have understood your question correctly.
protected void Page_Load(object sender, System.EventArgs e)
	if (!page.ispostback()) {
		string _id = Request.QueryString("id");
		using (SqlClient.SqlConnection _o = new SqlClient.SqlConnection("myconnectionstring...")) {
			using (SqlClient.SqlCommand _c = new SqlClient.SqlCommand()) {
				_c.Connection = _o;
				_c.CommandText = "SELECT * FROM MyTable WHERE ID=" + _id;
				_c.CommandType = CommandType.Text;
				using (SqlClient.SqlDataReader _r = .ExecuteReader) {
					if (_r.Read) {
						// Fill your form from the reader:
						txtMyField.text = _r("MyField").ToString;

Open in new window

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now