0

I have a method to show a value in a TextBox:

public double sumaEntregasDos(int id)
{
    conectar();
    //cmd2.CommandText = "SELECT SUM(pc.entrega) FROM PagosClientes pc INNER JOIN Clientes c ON pc.idCliente = c.idCliente WHERE c.nombre = @nombreCliente";
    //cmd2.Parameters.AddWithValue("@nombreCliente", nombre);

    cmd2.CommandText = "SELECT SUM(entrega) FROM PagosClientes WHERE idCliente in (" + 
        id + ")";

    double suma = Convert.ToDouble(cmd2.ExecuteScalar());
    desconectar();
    return suma;
}

When I press the Button, the program shows me the following error:

Object cannot be cast from DBNull to other types.

How can I solve this problem?

Rufus L
  • 36,127
  • 5
  • 30
  • 43
  • One solution may be to provide a NULL value condition in case that the sum on entrega is not able to be calculated. – alexherm Feb 17 '21 at 00:56
  • I don't know how, 'cause the problem is in the line `double suma = Convert.ToDouble(cmd2.ExecuteScalar());` –  Feb 17 '21 at 01:02
  • Does this answer your question? [Handling ExecuteScalar() when no results are returned](https://stackoverflow.com/questions/1999020/handling-executescalar-when-no-results-are-returned) – quaabaam Feb 17 '21 at 01:04

1 Answers1

0

The standard way is to check for DBNull:

var result = cmd2.ExecuteScalar();
return result == DBNull.Value ? default : (double)result;

It's a bit cumbersome, so often it's easier to just write SELECT ISNULL(..., 0) ...

Further points:

  • This only applies if you get an actual NULL result. If there are no rows at all then you need to check for null instead of DBNull.Value
  • If you do have a null value you need to handle, the above code also works for double?
  • Obviously use your commented out code instead which uses parameters properly, instead of the code you actually have. Please note that AddWithValue is evil, you should specify the actual SqlDbType, although in the case of int it doesn't really matter.
  • It looks like you are caching your connection object. You should not do this. Instead, create it on the spot, and dispose it in a using block.
Charlieface
  • 52,284
  • 6
  • 19
  • 43