V.David V.David - 2 months ago 5
C# Question

Asp.net Auto-increment data (That comes from database) to a variable -Error Object Cannot be cast from DBNull

It keeps appearing this error

"Object cannot be cast from DBNull to other types."

on
totaldevotos += Convert.ToInt32(dr["Classificacao"])
,

im trying to convert the object that comes from the database
"Classificacao"
into a
Integer
, (its a Int field on the Database), any ideas?

string sql = "SELECT * from Users LEFT JOIN Cocktails on Users.ID_Utilizador=Cocktails.ID_utilizador1 LEFT JOIN Rating on Cocktails.ID_cocktail=Rating.ID_cocktail WHERE Cocktails.ID_utilizador1=Users.ID_utilizador AND Users.ID_utilizador=" + ID;
int totaldevotos = 0;
SqlDataReader dr = con.query(sql);
while (dr.Read())
{
if (dr.HasRows)
{
totaldevotos += Convert.ToInt32(dr["Classificacao"]);
}
}

Answer

The value in the database is NULL for at least some rows.

Before you try to parse the value, check to see if it's null.

if (dr.HasRows)
{
    while (dr.Read())
    {
        if (dr["Classificacao"] != DBNull.Value)
        {
            totaldevotos += Convert.ToInt32(dr["Classificacao"]);
        }
    }
}

Also, you only need to check dr.HasRows once, before you start the loop.

Comments