Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 935
Mark Avatar asked Nov 03 '11 16:11

Mark


1 Answers

Change your reading code to:

while (reader.Read())
{
    if(reader.IsDBNull(reader.GetOrdinal("TopID")))
       topID = 0;
    else
       topID = Convert.ToInt32(reader["TopID"]);
}
like image 144
marc_s Avatar answered Oct 27 '22 19:10

marc_s