2014-01-27 31 views
1

我是開發新手,我想將插入行的最後一個密鑰ID顯示到標籤中。我有的代碼不會將值返回到標籤中。將範圍ID的值返回到標籤

代碼,我有:

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; 

      } 
     } 
+0

你有什麼看起來像它應該工作 - 從[MSDN](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar其直( v = vs.110)的.aspx)。可能嘗試在'INSERT INTO'之前添加一個'SET NOCOUNT ON'? – StuartLC

回答

1

您的代碼看起來像它應該工作。唯一要改變的是最後一行。將.ToString()添加到最後。

Label1.Text = newID.ToString(); 
+0

即使使用.toString(),這不起作用? – user3012159

+0

你的代碼看起來不錯;我一直在做類似的事情。我懷疑你的問題不在於這段代碼。嘗試在別處設置標籤文本並查看標籤文本是否更改。 –

+1

非常感謝。該標籤有錯誤的ID。 – user3012159