1
I am trying to return the largest ID of the table Orcamento in a variable, but it returns me an error:
An unhandled Exception of type 'System.Nullreferenceexception' occurred in Mysql.Data.dll. Additional information: reference to object not defined for an object instance."
Does anyone know what it can be?
Follows the code:
public void ultimoID(int ultimoid)
{
int resultado;
var conn = new MySqlConnection(stringCon);
var sql = "SELECT MAX(id_orcamento)FROM orcamento";
var cmd = new MySqlCommand(sql, conn);
Object retorno = cmd.ExecuteScalar();
resultado = Convert.ToInt32(retorno);
}
On which line is the error??
– Maniero
In this one: Object return = cmd.Executescalar();
– Jessf
You need to see why you can’t create
MySqlCommand
, the error is there.– Maniero
I got it rolling! This was missing: // Executes the cosulta cmd = new Mysqlcommand(sql, Conn); rdr = cmd.Executereader(); while (rdr.Read()) while (rdr.Read()) { string result = rdr["MAX(id_orcamento)"]. Tostring(); int resultadoid = Convert.Toint32(result); this.ultimoValor = resultadoid; }
– Jessf
This may have worked, but it’s a coincidence, and it’s a scam, because this isn’t a case for using the Reader, the correct is the scalar same. Still have error that the connection is not closed, which may be the problem. And the code can be written in 1 line.
– Maniero
got it, I tried it this way, but it gives the same error. I took only the expression and ran it in Mysql and it returns the correct result.
– Jessf