Thursday, April 19, 2012

Object cannot be cast from DBNull to other types. How to resolve this Exception Message?

Error Message: Object cannot be cast from DBNull to other types.

Solution: This exception occurred because the data type of data column of data row accepts null values, but the data type in C# not. All the data type that are "value types" (struct) don´t accepts null values.

In this case, You must to calls dr.IsNull(0) or to implement nullable datatype in year field ( int? year; if you have using .NET 2).

Below code will works fine.

if (_dRow["ColumnName"] != DBNull.Value)
       string myDate = Convert.ToDateTime(_dRow["ColumnName"]).ToString("dd-MMM-yyyy");

Please read below remarks for DBNull according to MSDN online.

The DBNull type is a singleton class, which means only one DBNull object exists. The DBNull.Value member represents the sole DBNull object. DBNull.Value can be used to explicitly assign a nonexistent value to a database field, although most ADO.NET data providers automatically assign values of DBNull when a field does not have a valid value. You can determine whether a value retrieved from a database field is a DBNull value by passing the value of that field to the DBNull.Value.Equals method. However, some languages and database objects supply methods that make it easier to determine whether the value of a database field is DBNull.Value. These include the Visual Basic IsDBNullfunction, the Convert.IsDBNull method, the DataTableReader.IsDBNull method, and the IDataRecord.IsDBNull method.

No comments:

Post a Comment