John Steed
John Steed

Reputation: 629

Unable to set the default value of a string variable to DBNull

My understanding is that the datatype Stringin VB.NET is nullable.

Therefore, I don't understand why the following code returns the error "Value of DBNull Cannot Be Converted To String"

Public name As String = DBNull.Value

For context, I have a class whose values will be written to a database. When the class's object is created, it is possible that not all its variables will have values. I want missing values to be null in the database, so therefore I intended to set the variables' default value to DBNull as above. But this isn't working due to the error above.

Upvotes: 0

Views: 709

Answers (3)

Andrew Morton
Andrew Morton

Reputation: 25027

To do what you want with the writes to the database, you can use Nothing for the value and then, when writing to the database, check for yourString Is Nothing and if so then set the parameter's value to DBNull.Value.

Public Class Datum
    Property Name As String = Nothing
End Class

Sub X()
    Dim q As New Datum

    Using cmd As New SqlCommand()
        ' other code...

        cmd.Parameters.Add(New SqlParameter With {.ParameterName = "@Name", .SqlDbType = SqlDbType.NVarChar, .Size = 123})
        If q.Name Is Nothing Then
            cmd.Parameters("@Name").Value = DBNull.Value
        Else
            cmd.Parameters("@Name").Value = q.Name
        End If

        ' other code....
    End Using

End Sub

N.B. For correct operation, use the Is and IsNot operators when checking for Nothing, do not use the = operator.

Upvotes: 0

Icemanind
Icemanind

Reputation: 48696

DBNull is not really equivalent to Nothing. It is a class. Value is a shared field of the DBNull object, which just sets the value of Value to an instance of the DBNull class. You can see this for yourself here.

Upvotes: 2

daShier
daShier

Reputation: 2116

DBNull can't be converted to a string, you need to test for it. You can assign Nothing to a string, so you can use:

    Public name As String = Nothing

Upvotes: 0

Related Questions