0

I have this in my VB.NET code:

Dim myValue as String
myValue = ""
Dim myDblValue as Double
myDblValue CDbl(Val(myValue))

If myValue string is null [like in this example], I'd like to set the value to a predefined value for example 999. I know in SQL I can use ISNULL for that. Is there any equivalent in VB.NET? If not, how can it be done with available functions?

D. Caan
  • 1,907
  • 6
  • 22
  • 36

4 Answers4

2

To directly answer your question, IF operator is the nearest to ISNULL when used with the String.IsNull method.

Like this

    Dim myValue As String
    myValue = ""
    Dim myDblValue As Double

    Dim myDefaultValue As Double = 10.1 ' what ever you need

    myDblValue = If(String.IsNullOrEmpty(myValue), myDefaultValue, CDbl(myValue))

If you need to worry about invalid text in myValue then you can use the Double.TryParse method like this.

    Dim myValue As String
    myValue = ""
    Dim myDblValue As Double

    Dim myDefaultValue As Double = 10.1 ' what ever you need

    If String.IsNullOrEmpty(myValue) OrElse Not Double.TryParse(myValue, myDblValue) Then
        myDblValue = myDefaultValue
    End If
Gridly
  • 938
  • 11
  • 13
  • Using IIF in this way will generate an exception if `myValue` is Nothing because both all of the expressions in the IIF fuction will be evaluated (including the `CDbl`. IIF does not short circuit. – Chris Dunaway Jun 11 '14 at 13:43
1
If YourVariable.IsNullOrEmpty Then
     myValue = DoWhateverYouWant
Else
     DoOtherStuff
End If
Mark C.
  • 6,332
  • 4
  • 35
  • 71
  • Just `If(myValue.IsNullOrEmpty, 999, ???)`. IIf has been depricated because it evaluates both the true and false expressions. – Jonathan Allen Jun 11 '14 at 00:17
  • @JonathanAllen thanks for clearing that up. Is there a link you can provide? I looked before I posted but didn't find anything. – Mark C. Jun 11 '14 at 00:20
1

You can use the String Methods IsNullOrEmpty or IsNullOrWhiteSpace to create you own function something like this.

Public Function TestNull(value As String, defaultValue As String) as String
    If String.IsNullOrEmpty(value) Then
        Return defaultValue
    Else
        Return value
    End If
End Function

Usuage:

myDblValue = CDbl(Val(TestNull(myValue, "999")))

Or since you are converting to a double you can just use the Double.TryParse Method it will fail if it can't be converted for any reason

Public Function TestValidDecimal(value As String, defaultValue As Double) As Double
    Dim temp As Double
    If Double.TryParse(value, temp) Then
        Return temp
    Else
        Return defaultValue
    End If
End Function
Mark Hall
  • 53,938
  • 9
  • 94
  • 111
0

myDblValue = If(myValue = Nothing, 999, CDbl(Val(myValue)))

OR

myDblValue = If(myValue = "", 999, CDbl(Val(myValue)))

SEE:

http://msdn.microsoft.com/en-us/library/bb513985(v=vs.90).aspx

Tom
  • 41
  • 4