hardywang
hardywang

Reputation: 5162

Nullable object must have a value. in VB.NET

I have following code in VB.NET:

Public Sub Test(ByRef clientId As Nullable(Of Integer))
    Dim t As Object = IIf(clientId.HasValue, clientId.Value, DBNull.Value)
End Sub

The calling side pass in Nothing as clientId value, but when I run this statement I got exception.

Nullable object must have a value

Is my statement wrong?

Upvotes: 2

Views: 4493

Answers (2)

TALAL
TALAL

Reputation: 1

 Dim cp As Single
        '    Try
If tt.getsumpaid4cors(CInt(sidtxt.Text), CInt(coidtxt.Text), CInt(tidtxt.Text), CInt(stidtxt.Text)).HasValue Then

            cp = tt.getsumpaid4cors(CInt(sidtxt.Text), CInt(coidtxt.Text), CInt(tidtxt.Text), CInt(stidtxt.Text)).Value
        Else
            cp = 0
End If

Upvotes: -2

Dave Doknjas
Dave Doknjas

Reputation: 6542

Change it to use "If":

Dim t As Object = If(clientId.HasValue, clientId.Value, DBNull.Value)

The problem with "IIf" is that it's just a function call - all arguments are always evaluated, while the VB 'If' operator behaves like the '?' operator in C#/Java - it only evaluates what it needs to evaluate.

Upvotes: 5

Related Questions