Reputation: 21430
I have a null value in my database which gives me an error if I try perform any mathematical operations on it. I tried putting this in my controller action:
If String.IsNullOrEmpty(item.Tbl_Food.Fiber_TD_g) Then
item.Tbl_Food.Fiber_TD_g = 0
End If
This my model for the field:
Public Property Fiber_TD_g() As Nullable(Of Double)
However, it says "Nullable object must have a value." on the If String.IsNullOrEmpty(item.Tbl_Food.Fiber_TD_g) Then
line. How can I check if the "string" (it's a double, not a string) is empty and default it to zero, properly?
Edit:
I tried a suggestion below, and I no longer get an error in my controller, but instead in my View. It says, "Nullable object must have a value." on the line FiberTotal += item.Tbl_Food.Fiber_TD_g
in my view.
Dim food = db.Tbl_Food_Logs.Where(Function(x) x.FLog_Employee_ID = empId And x.FLog_Created_Date >= date2 And x.FLog_Created_Date < tomorrow)
For Each item In food
If IsDBNull(item.Tbl_Food.Fiber_TD_g) Then
item.Tbl_Food.Fiber_TD_g = 0
End If
Next
Return View(food)
Upvotes: 0
Views: 1956
Reputation: 1083
If IsNull(item.Tbl_Food.Fiber_TD_g) Then
item.Tbl_Food.Fiber_TD_g = 0
End If
or
If Trim(item.Tbl_Food.Fiber_TD_g) Then
item.Tbl_Food.Fiber_TD_g = 0
End If
Upvotes: 2
Reputation: 11233
You can also check for:
If item.Tbl_Food.Fiber_TD_g.Equals(Nothing) Then
item.Tbl_Food.Fiber_TD_g = 0
End If
Upvotes: 0
Reputation: 86708
As its name implies, String.IsNullOrEmpty
is a string operation. It won't work if you pass a double
. Instead check to see if it Is Nothing
:
If item.Tbl_Food.Fiber_TD_g Is Nothing Then
item.Tbl_Food.Fiber_TD_g = 0
End If
This operation is common enough that VB has a shortcut, called the null coalescing operator (2-argument If
):
item.Tbl_Food.Fiber_TD_g = If(item.Tbl_Food.Fiber_TD_g, 0)
When If
has two arguments, it returns the first argument if it's not null and the second if it is.
Upvotes: 3
Reputation: 13286
item.Tbl_Food.Fiber_TD_g = item.Tbl_Food.Fiber_TD_GetValueOrDefault()
Upvotes: 0
Reputation: 7445
Change model part to:
public double? Fiber_TD_g { get; set; }
and then
item.Tbl_Food.Fiber_TD_g = item.Tbl_Food.Fiber_TD_g.HasValue ? item.Tbl_Food.Fiber_TD_g.Value : 0;
Upvotes: 0
Reputation: 2788
You can think of string IsNullOrEmpty as checking for an uninitialiaed string variable, not as a check for an object being null. I think you want something like this, for maximum security.
If Not item Is Nothing Then
If Not item.TBL_food Is Nothing Then
If Not item.Tbl_Food.Fiber_TD_g Is Nothing Then
'do something
End If
End If
End If
Upvotes: 1