An object-oriented programming language developed by Microsoft that can be used in .NET.
Hi @Corey H ,
Thanks for reaching out.
This would happen when the value coming back from the database is actually NULL. In .NET, that comes through as DBNull.Value, which represents a database null and cannot be cast directly to a String.
The appropriate approach is to check for DBNull before assigning the value to a string, then use a safe default such as an empty string if the database field is null.
For example, if you are reading from a DataRow, you can do this:
Dim value As Object = row("SomeColumn")
Dim text As String
If value Is DBNull.Value Then
text = String.Empty
Else
text = CStr(value)
End If
Or, if you prefer a shorter version:
Dim value As Object = row("SomeColumn")
Dim text As String = If(IsDBNull(value), String.Empty, CStr(value))
If you are using a DataReader, this pattern is usually cleaner:
Dim columnIndex As Integer = reader.GetOrdinal("SomeColumn")
Dim text As String
If reader.IsDBNull(columnIndex) Then
text = String.Empty
Else
text = reader.GetString(columnIndex)
End If
You can replace String.Empty with another fallback value, such as "N/A", if that makes more sense for your application.
Hope this helps! If my explanation and the information I provided were helpful, I would greatly appreciate it if you could follow the instructions here so others with the same problem can benefit as well.