In this article learn how to get last inserted value in a table. When we insert data into table we get the last identity value using @@IDENTITY.
private void insertProduct()
{
SqlConnection myConnection;
try
{
myConnection = new SqlConnection((string)Session["DBConnector"]);
myConnection.Open();
StringBuilder sql = new StringBuilder();
SqlCommand myCommand = new SqlCommand("usp_InsertProduct", myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.Clear();
myCommand.Parameters.Add("@Name", txtName.Text);
myCommand.ExecuteNonQuery();
myCommand = new SqlCommand("SELECT @@IDENTITY", myConnection);
int ProductId = Convert.ToInt32(myCommand.ExecuteScalar());
}
catch (Exception ex)
{
//Something went wrong
throw;
}
finally
{
myConnection.Close();
//Finally, close the connection
}
}