[英]Retrieve the most recent primary key from database after form submission C#
I have a Webforms project and I have the information going into a database. 我有一个Webforms项目,并且信息已进入数据库。 My question is, after submitting the page, how can I retrieve and display the newly created
ID
(primary key) on the next page in a label? 我的问题是,提交页面后,如何在标签的下一页上检索并显示新创建的
ID
(主键)? Is this even possible to do? 这有可能吗?
I have this code for retrieving the ID based of an old project I did: 我有这段代码用于检索我做过的旧项目的ID:
SqlCommand da3 = new SqlCommand(strSelectCmd3, conn);
da3.CommandType = CommandType.StoredProcedure;
SqlDataAdapter ds3 = new SqlDataAdapter();
ds3.SelectCommand = da3;
DataSet dsPerson3 = new DataSet();
ds3.Fill(dsPerson3);
Response.Redirect("Submitted.aspx?ID=" + dsPerson3.Tables[0].Rows[0]["CremationID"].ToString());
In your insert SQL stored procedure, either SELECT the SCOPE_IDENTITY() directly, or set an output variable to that. 在您的插入SQL存储过程中,直接选择SCOPE_IDENTITY()或为其设置输出变量。 This will give you the PK for this table.
这将为您提供此表的PK。
You can then use that id as a part of the query string for the next page. 然后,您可以将该ID用作下一页查询字符串的一部分。 This will allow you to load that page without needing to make a separate call to the database, and you will be guaranteed to have the correct id.
这样,您就可以加载该页面,而无需对数据库进行单独调用,并且可以保证您具有正确的ID。
Trying to figure out the last id without using something scope-specific like this (such as SCOPE_IDENTITY), will have the issue that you might receive an Id inserted by another process / user on the page, rather than the one just handled. 尝试在不使用类似范围的特定内容(例如SCOPE_IDENTITY)的情况下找出最后一个ID,将会遇到一个问题,即您可能会收到页面上另一个进程/用户(而不是刚刚处理的一个)插入的ID。
I added this statement inside of my stored procedure: 我在存储过程中添加了以下语句:
SELECT TOP (1) CremationID, Last, First
FROM dbo.Cremation
WHERE (Last = @Last) AND (First = @First)
ORDER BY CremationID DESC
And then on the new pages inserted a label and put this code inside of the Page_Load 然后在新页面上插入标签,并将此代码放在Page_Load内
CID.Text = Request.QueryString["ID"].ToString();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.