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;
Instead of:
Do:
When the
dr["result"]returns a databasenull, its value isDbNull.Value– when you try to callConvert.ToInt32on this value, you get a format exception.