If a column in a DataRow
might be DBNull
, is the following the shortest way to substitute an empty string for DBNull
?
Dim result As String = if(isDBNull(dataRow1("column1")), "", dataRow1("column1"))
If a column in a DataRow
might be DBNull
, is the following the shortest way to substitute an empty string for DBNull
?
Dim result As String = if(isDBNull(dataRow1("column1")), "", dataRow1("column1"))
Just use the Field(Of T)
methods, which will convert DBNull
values to Nothing
for you. Also, they are typesafe.
Dim result = If(dataRow1.Field(Of String)("column1"), String.Empty)
you might want to create an extension method for ease of use (not tested):
Imports System.Data
Imports System.Runtime.CompilerServices
Module Extensions
<Extension()>
Public Function GetStringValue(dataRow As DataRow, columnName As String, Optional substituesForDBNull As String = Nothing) As String
If IsDBNull(dataRow(columnName)) Then
Return substituesForDBNull
End If
Return CStr(dataRow(columnName))
End Function
End Module