I am new to development and I want to show the last key id of an inserted row into a label. The code I have does not return the value into the label.

Code I have:

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;

            }
        }
有帮助吗?

解决方案

Your code looks like it should work. The only thing to change is the last line. Add .ToString() to the end.

Label1.Text = newID.ToString();
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top