Pages

Tuesday, October 6, 2009

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

When trying to assign data from a datasource to string variables where some of the fields contained null values i was was getting the following error.

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

I know this is really simple stuff but as a beginner it took me a while to figure this out. If you use the Convert.ToString method then even though your data may be the correct datatype to start with it will convert a null value to an empty string instead of throwing the above error.


MyStringVariable = Convert.ToString(myDataReader["MyDBFieldName"]);
 
 

Blogger