C# 将作用域ID的值返回到标签
我是开发新手,我想在标签中显示插入行的最后一个键id。我的代码没有将值返回到标签中 我有:C# 将作用域ID的值返回到标签,c#,sql,label,scope-identity,C#,Sql,Label,Scope Identity,我是开发新手,我想在标签中显示插入行的最后一个键id。我的代码没有将值返回到标签中 我有: using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Users"].ConnectionString)) { var cmd = "INSERT INTO Quote (Customer, Date)VALUES (@Customer, @Date);SELECT
using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Users"].ConnectionString))
{
var cmd = "INSERT INTO Quote (Customer, Date)VALUES (@Customer, @Date);SELECT CAST(scope_identity() AS int)";
using (var insertCommand = new SqlCommand(cmd, conn))
{
int newID;
insertCommand.Parameters.AddWithValue("@Customer", TextBox12.Text);
insertCommand.Parameters.AddWithValue("@Date", DateTime.Now);
conn.Open();
newID = (int)insertCommand.ExecuteScalar();
Label1.Text = newID;
}
}
您的代码看起来应该可以工作。唯一需要更改的是最后一行。将
.ToString()
添加到末尾
Label1.Text = newID.ToString();
你所拥有的东西看起来应该能用——它是直接从。在
插入到
之前,可能尝试添加一个设置NOCOUNT ON
?您的代码看起来很好;我一直在做类似的事情。我怀疑你的问题不在于这段代码。尝试在其他位置设置标签文本,并查看标签文本是否更改。