Pergunta

I am trying to use the If() Operator to coalesce values in a SQL Parameter but I am having trouble figured it out.

Dim First as String = Nothing
First = FirstName.Text
Using conn As New SqlConnection()
'Code omitted
.AddWithValue("@FirstName", If(First, DBNull.Value))

Basically, if First = Nothing, the Parameter should be formatted like:

.AddWithValue("@FirstName", DBNull.Value)

If FirstName.Text is not Nothing or Null then it would basically be like:

.AddWithValue("@FirstName", First)

Anyone have any pointers or have any suggestions?

I understand that First is carrying a value of "", I am just not sure how to program around that. That's why I tried = Nothing.

This is currently being written like:

If employeeName <> "last,first" Then
    cmd.Parameters.AddWithValue("@EMPL_NM", employeeName)
Else
    cmd.Parameters.AddWithValue("@EMPL_NM", DBNull.Value)
End If

Which I'm trying to reduce to

.AddWithValue("@FirstName", If(First, DBNull.Value))
Foi útil?

Solução

DBNull.Value and String are different types. The null-coalescing operator doesn't like that.

You could cast it to Object to make it compile, although i would prefer your If-Else:

cmd.Parameters.AddWithValue("@FirstName", If(First, DirectCast(DBNull.Value, Object)))
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top