Tuesday, March 20, 2012

C#/VB.NET - Object cannot be cast from DBNull to other types | .NET Exception | Error


Issue:
"Object cannot be cast from DBNull to other types" - Error / Exception in .NET / ASP.NET / ADO.NET

While executing the below code it throws and exception "Object cannot be cast from DBNull to other types".

while (reader.Read())  
 {  
   age = Convert.ToInt32(reader[0]);  
 }  

This is a common mistake from novice .net developers.

Reason:
The error occurs because the field fetched by the DataReader has a database value null. This null value is attempted to convert to type int and thus the error "Object cannot be cast from DBNull to other types". If "Allow Null" is enabled for this field in the database and it contains null, then there is a possibility for this error.

Solution:
Do a check for null before trying to access the value from the DataReader. Both solution 1) and solution 2) should work.

Solution 1)
 while (dr.Read())  
 {  
   if(!reader.IsDBNull(0))  
   {  
     age = reader.GetInt32(0);  
   }  
 }  

Solution 2)
 while (dr.Read())  
 {  
 if (reader[0] != DBNull.Value)  
 age = Convert.ToInt32(reader[0]);  
 }  


No comments:

Post a Comment