c# .net Adsense ADO.NET Linq Viruses/security asp.net MVC JQuery Angular-js Node-js SEO Java C++ SQL API Networking vb.net .Net Css JavaScript Generics c#.Net entity framework HTML Website host Website Construction Guide HTTP tutorial W3C tutorial Web Services JSON Psychology Ionic framework Angular ReactJS Python Computer Android
c# .net

How to get last inserted value from a table using c# ?

| | ASP-NET , CSharp

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
}

}