Reputation: 2859
When i execute this command on my database i receive sometimes result=null. i want to enter the "else" part when is this happening, but i receive
An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll. Additional information: Input string was not in a correct format.
DB database = new DB();
int reservedSeats = 0;
using (database.sqlConnection)
{
database.sqlConnection.Open();
string command = "select SUM(nrLocuri) as result from Rezervari where idRand = @idRand and idShow=@idShow";
using (SqlCommand cmd = new SqlCommand(command, database.sqlConnection))
{
cmd.Parameters.Add("@idRand", SqlDbType.Int).Value = idRand;
cmd.Parameters.Add("@idShow", SqlDbType.Int).Value = idShow;
using (SqlDataReader dr = cmd.ExecuteReader())
{
if (dr.Read())
if (dr["result"].ToString() != null)
reservedSeats = Convert.ToInt32(dr["result"].ToString());
else
return totalSeats;
}
}
}
return totalSeats-reservedSeats;
Upvotes: 0
Views: 113
Reputation: 34152
try:
if(!dr.IsDBNull(i)){ //replace i with the column id
//get the data
}
Upvotes: 2
Reputation: 498914
Instead of:
if (dr["result"].ToString() != null)
Do:
if (dr["result"] != DbNull.Value)
When the dr["result"]
returns a database null
, its value is DbNull.Value
- when you try to call Convert.ToInt32
on this value, you get a format exception.
Upvotes: 6
Reputation: 22323
try isnull
:
string command = "select isnull(SUM(nrLocuri),0.00 )as result from Rezervari where idRand = @idRand and idShow=@idShow";
Upvotes: 1
Reputation: 137262
If you want SUM()
to return 0.00
in the event no records were found, replace it with:
COALESCE(SUM(...), 0.00)
COALESCE will return the first non-null value passed to it.
Upvotes: 1