• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 362
  • 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#.
0
devnewbee
Asked:
devnewbee
1 Solution
 
kssoftwareCommented:
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.
Chris
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...")) {
			_o.Open();
			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;
					}
					_r.Close();
 
				}
 
			}
 
			_o.Close();
			_o.Dispose();
 
 
		}
	}
}

Open in new window

0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

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