1

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))
0

1 Answer 1

1

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)))
Sign up to request clarification or add additional context in comments.

2 Comments

Damnet. I thought it would have something to do with that. Thanks! Do you think the If/Else is more efficient?
@Newbie: it's not more efficient but it's clear and also enables to write additional code, for example if you want to handle the case that First is Nothing (message-box, log etc).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.