show last record of a table in c # with sql server

0

What I try to do is capture the last code that was entered from my table in sql and show it in my txt that is in c # try with this code but it did not work for me I hope your help

  SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Conexion"].ConnectionString);
            SqlCommand com = new SqlCommand("select Nro_Pedido from pedido where nro_pedido= (select @@IDENTITY)", con);
            con.Open();
            SqlDataReader nro = com.ExecuteReader();
            if (nro.Read())
            {
                txtnum_ped.Text = nro["Nro_pedido"].ToString();

            }
            con.Close();
    
asked by Dannylo Ramos 26.11.2018 в 06:43
source

1 answer

1

I did the same with the ID_Sell and so get the last and only add 1 and for a new sale.

**
String id_ultima = "SELECT distinct TOP 1 (ID_Ventas) FROM TablaVentas ORDER BY ID_Ventas DESC";
    SqlConnection Con = new SqlConnection("Data Source=.;Initial Catalog=XtremeFoodV2;Integrated Security=True");
    SqlCommand ejecutar = new SqlCommand(id_ultima, Con);
    Con.Open();
    SqlDataReader leer = ejecutar.ExecuteReader(); 
    if (leer.Read() == true)
    {
        ultimo = Convert.ToInt32(leer["ID_Ventas"].ToString());
        ultimo++;
        Con.Close();
    }

**

I hope it serves you. By the way, this can cause an error if in case your table is empty, since you will get a null value and it will not add 1, what you can do to solve it is to add an empty record to Start at 0 or default to your database with the value 0.

    
answered by 26.11.2018 / 08:33
source