質問

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.

役に立ちましたか?

解決

Since your if is executing, your else if will not execute.

If you want your else if logic to execute even if your if executes, just make it it's own if block:

If row.Item(2) Is Nothing OrElse row.Item(2).ToString = "" OrElse IsDBNull(row.Item(2)) Then
    dt.Rows.Item(i).SetField(2, 0)
End If

If 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

他のヒント

You don't provide sample data so we just have to guess. But my guess is that you want two If statements.. not an ElseIf. ElseIf will only evaluate if the If statement returns false.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top