An object-oriented programming language developed by Microsoft that can be used in .NET.
InvalidCastException: Conversion from type 'DBNull' to type 'String' is not valid occurs because code is trying to cast or convert a database null (DBNull.Value) directly to String, which is not a supported conversion.
To fix it, always check for DBNull before converting, and provide a replacement value when the database field is null. Typical VB patterns:
' Example: reading from a DataRow or DataReader
Dim value As Object = row("SomeColumn") ' or reader("SomeColumn")
Dim text As String
If value Is DBNull.Value Then
text = String.Empty ' or a default like "N/A"
Else
text = CStr(value) ' safe because it is not DBNull
End If
Or using IIf/If for brevity:
Dim text As String = If(IsDBNull(row("SomeColumn")), String.Empty, CStr(row("SomeColumn")))
Key points:
-
DBNullis a special type used by ADO.NET to represent database NULL; it cannot be cast directly toString. - Conversions that are not supported throw
InvalidCastExceptionand should be fixed in code rather than caught and ignored. - Use
ConvertorCStronly after confirming the value is notDBNull.
References:
- Cast from string "<string>" to type '<typename>' is not valid
- Cast from type '<typename1>' to type '<typename2>' is not valid
- System.InvalidCastException class
- DBNull.IConvertible.ToType(Type, IFormatProvider) Method
- DBNull.IConvertible.ToChar(IFormatProvider) Method
- Type conversion in .NET
- Casting and type conversions (C# Programming Guide)