2014-01-08 68 views
1
Dim dr As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection) 
Dim dt As DataTable = New DataTable() 
dt.Load(dr) 

For Each row As DataRow In dt.Rows 

    Dim dob_str As String = "" 

    'code to check if row.Field(Of Date)("DOB") is dbnull 
    'if not dbnull then dob_str = row.Field(Of Date)("DOB") 

Next 

如何檢查DataTable中每行的Date類型列是否爲空?檢查數據表中的日期列是否爲

我試圖

If Not row.Field(Of Date)("DOB") = Nothing Then 
     dob_str = row.Field(Of Date)("DOB") 
    End If 

Dim nullCheck As Boolean = IsDBNull(row.Field(Of Date)("DOB")) 
    If nullCheck = False Then 
     dob_str = row.Field(Of Date)("DOB") 
    End If 

,但他們都在運行時導致Cannot cast DBNull.Value to type 'System.DateTime'. Please use a nullable type.

回答

1

使用Nullable

If row.Field(Of Date?)("DOB") IsNot Nothing Then 
    dob_str = row.Field(Of Date)("DOB") 
End If 

或者

If row.Field(Of Date?)("DOB").HasValue Then 
    dob_str = row.Field(Of Date)("DOB") 
End If 

或者使用IsNull

If Not row.IsNull("DOB") Then 
    dob_str = row.Field(Of Date)("DOB") 
End If 
+0

如果你不使用'是Nothing'而不是'= Nothing'? –

+0

'如果不是... = Nothing'會導致警告消息'由於來自等號運算符的空傳播,此表達式總是計算爲Nothing。要檢查值是否爲空,請考慮使用'是Nothing'。' –

+0

@j_t_fusion對不起,我從事VB.NET工作已經有一段時間了。糾正。 –

相關問題