I imported an Excel file into an ASP.NET DataTable. Some of the values are blank, specifically at indexes 2 and 3, and I would like to set those blank fields to 0
.
When debugging, the values for row.item(2)
and row.item(3)
are both System.DBNull
. Interestingly enough, the program enters the If
statement and sets row.item(2)
value to 0, but it never enters the ElseIf
statement. What is going on? Here's my code:
If row.Item(2) Is Nothing OrElse row.Item(2).ToString = "" OrElse IsDBNull(row.Item(2)) Then
dt.Rows.Item(i).SetField(2, 0)
ElseIf row.Item(3) Is Nothing OrElse row.Item(3).ToString = "" OrElse IsDBNull(row.Item(3)) Then
dt.Rows.Item(i).SetField(3, 0)
End If
EDIT:
Per Tim's suggestion, I revised my code as follows:
If Not row.Field(Of Int32?)(2).HasValue Then
dt.Rows.Item(i).SetField(2, 0)
End If
If Not row.Field(Of Int32?)(3).HasValue Then
dt.Rows.Item(i).SetField(3, 0)
End If
However, this is throwing an error--Object cannot be cast from DBNull to other types
When debugging, in the first loop:
row.Item(2) = 17
row.Item(3) = 1
Theoretically, it should skip this iteration and proceed to the next. However, my program immediately catches the exception with the above error.