Sunday, January 20, 2013

Exception: Unable to cast object of type 'System.DBNull' to type 'System.String'.

Exception: When you try to convert a DBNull value to string this error will occur.


Description: DBNull is not equivalent to null. As DBNull is a different type. So it can not be converted to string.


Fix: ADO.NET mostly returns DBNull for database null value.


ToString() on DBNull value will return empty string

Convert.IsDBNull will return true if the given value is null




String s = dr[“column”] ; // will throw error

String s= dr[“column”].ToString()l //will save empty string instead of null

String s= Convert.IsDBNull(dr[“column”])?null:dr[“column”]; // will save null for DBNull value

No comments:

Post a Comment