0
I’m trying to make a method that returns the last record of the table but gives error:
Failure in operation"coditem"
public int UltimoItem()
{
con = conexao.obterConexao();
try
{
cmd = new SqlCommand("SELECT MAX(Cod_Item) FROM Pedidos_Itens", con);
cmd.CommandType = CommandType.Text;
SqlDataReader dr = cmd.ExecuteReader();
int Ultimo = 0;
while (dr.Read())
{
Ultimo = Convert.ToInt32(dr["Cod_Item"]);
}
return Ultimo;
}
catch (Exception ex)
{
throw new Exception("Falha na operação: " + ex.Message);
}
finally
{
con.Close();
}
}
The field
Cod_Item
exists?– Roberto de Campos
Try putting a alias for the return of the function MAX and return that same name on Convert
– Leandro Paixão
Depending on the database you are using, when you do "MAX" you have to give it a name, so "MAX(Cod_item) AS Cod_item" if not it returns the unnamed column, then when you try to access dr["Cod_item"] it does not find the column and the error. See if that’s the problem. That’s exactly what @Leandropaixão said in the answer above.
– Leandro Simões
SELECT Cod_Item FROM Pedidos_Itens order by Cod_Item desc limit 1
– R.Santos
Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site (when you have enough score).
– Maniero