VB .NET
Fix: Conversion from type 'DBNull' to type 'String' is not valid

VB.NET Conversion from type 'DBNull' to type 'String' is not valid
Error
Description: VB.NET runtime error stating: Conversion from type 'DBNull' to type 'String' is not valid.
Cause
This error typically occurs when your application tries to read a database field that is NULL (i.e., contains no data) and attempts to store it directly in a String
variable without validation.
Solution
To avoid this error, always validate or check for DBNull.Value
before assigning the field value to a variable.
If Not IsDBNull(dr("FullName")) Then
TxtFullName.Text = dr("FullName").ToString()
Else
TxtFullName.Text = ""
End If
This approach ensures that your application won't crash when it encounters NULL values.
Community Tip
According to developers on Stack Overflow, the error can be solved either:
- From your VB.NET code, by using validation techniques.
- Or by modifying your database default values to prevent NULLs.
Whichever solution you choose, always test the behavior when fields are empty. This error is common in WinForms applications connected to MS Access using OleDbDataReader
or DataSet
.
Bonus Tip
To simplify NULL handling across your application, consider writing a reusable function:
Function SafeString(ByVal field As Object) As String
If IsDBNull(field) Then
Return ""
Else
Return field.ToString()
End If
End Function
Then you can use it like this:
TxtFullName.Text = SafeString(dr("FullName"))
This pattern improves code readability and prevents repeated NULL checks everywhere.
♥ Here are some online Visual Basic lessons and courses: