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.