2012-01-18 47 views
3

在我的ASP.Net Web的應用程序後,我得到這個錯誤:「轉換,從類型‘爲DBNull’到類型‘布爾’是無效的」,檢查它不是DBNull的

Conversion from type 'DBNull' to type 'Boolean' is not valid.

從這個功能:

Namespace atc 
    Public Class Nil 
     '... 
     Public Shared Function Bool(ByVal Item As Object) As Boolean 
      Return IIf(Item IsNot Nothing AndAlso Not IsDBNull(Item), CBool(Item), False) 
     End Function 
     '... 
    End Class 
End Namespace 

正如你所看到的,我明確地檢查是否ItemDBNull,如果它是那麼我回到False

錯誤仍時ItemDBNull發生,所以我不明白爲什麼會這樣。

回答

10

當使用IIf那麼所有的參數得到評估,無論條件的計算結果爲真或假。在你的情況函數將返回false如果項目的DBNull,但CBool(Item)會默默地在後臺反正執行,因此拋出異常。

在2008 VB.NET中加入If關鍵字,以提供一個真正的三元運算符。用以下替換您IIf函數調用:

Public Shared Function Bool(ByVal Item As Object) As Boolean 
    Return If(Item IsNot Nothing AndAlso Not IsDBNull(Item), CBool(Item), False) 
End Function 

摘自MSDN

An IIf function always evaluates all three of its arguments, whereas an If operator that has three arguments evaluates only two of them.

相關問題