How to check for a Null value in VB.NET

Dan picture Dan · Dec 18, 2008 · Viewed 265.1k times · Source

I have this:

If String.IsNullOrEmpty(editTransactionRow.pay_id.ToString()) = False Then
    stTransactionPaymentID = editTransactionRow.pay_id 'Check for null value
End If

Now, when editTransactionRow.pay_id is Null Visual Basic throws an exception. Is there something wrong with this code?

Answer

Garry Shutler picture Garry Shutler · Dec 18, 2008

The equivalent of null in VB is Nothing so your check wants to be:

If editTransactionRow.pay_id IsNot Nothing Then
    stTransactionPaymentID = editTransactionRow.pay_id
End If

Or possibly, if you are actually wanting to check for a SQL null value:

If editTransactionRow.pay_id <> DbNull.Value Then
    ...
End If