Mark Mark - 3 months ago 15
C# Question

Object cannot be cast from DBNull to other types. Error when a null value is read by the Reader

int topID = 0;
string TopIDQuery = "Select TopID from tbl_Organisation where OrganisationID=@OrgID";

paramet[0] = new MySqlParameter("@OrgID", MySqlDbType.Int32);
paramet[0].Value = OrgID;

reader = server.ExecuteReader(CommandType.Text, TopIDQuery, paramet);

while (reader.Read())
{
topID = Convert.ToInt32(reader["TopID"]);
}

reader.Close();


I am reading the
topID
from the table, when the
TopID
is null I want to leave the
topID
as 0, but since it is null it is throwing a error, how can I handle this error when the
topID
is null

Answer

Change your reading code to:

while (reader.Read())
{
    if(reader.IsDBNull(reader.GetOrdinal("TopID")))
       topID = 0;
    else
       topID = Convert.ToInt32(reader["TopID"]);
}