2

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"))
CJ7
  • 22,579
  • 65
  • 193
  • 321
  • possible duplicate of [Change a datarow item from DBNull to a string value](http://stackoverflow.com/questions/15507675/change-a-datarow-item-from-dbnull-to-a-string-value) – Ken White Jul 25 '13 at 01:07
  • That does not look like valid C#. I think you want to use the ternary operator "? :" for that. – fcuesta Jul 25 '13 at 03:08

3 Answers3

2

dataRow1("column1") & "" will produce the desired result in VB.

CJ7
  • 22,579
  • 65
  • 193
  • 321
1

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)
sloth
  • 99,095
  • 21
  • 171
  • 219
0

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
Rex
  • 2,130
  • 11
  • 12