Share via

InvalidCastException

Corey H 0 Reputation points
2026-05-31T13:55:18.6366667+00:00

How to fix [InvalidCastException: Conversion from type 'DBNull' to type 'String' is not valid.]

Developer technologies | VB
0 comments No comments

1 answer

Sort by: Most helpful
  1. AI answer

    2026-05-31T13:55:27.5366667+00:00

    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:

    • DBNull is a special type used by ADO.NET to represent database NULL; it cannot be cast directly to String.
    • Conversions that are not supported throw InvalidCastException and should be fixed in code rather than caught and ignored.
    • Use Convert or CStr only after confirming the value is not DBNull.

    References:

    AI-generated content may be incorrect. Read our transparency notes for more information.

    Was this answer helpful?

    1 person found this answer helpful.

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.