我在以下几个月内从以下VB.NET代码中获取此异常:
System.InvalidCastException: Conversion from type 'DBNull' to type 'Date' is not valid.
它发生在这一行:
If CDate(dRow("CompleteDate")).ToString("d") = arrWeekYear(i, 1).ToString("d") Then
如果我理解正确,那么问题是我试图将CompleteDate的一些NULL值与非NULL值进行比较。
我该如何解决这个问题?对于某些日期,上面的代码运行完美。然而,对于一些最近的记录,它没有。但是我可以从具有相同日期范围的T-SQL查询中获得输出,并且没有错误;它也快速运行。我检查了这个T-SQL查询的“Date_Completed”和“Review_Date”NULL值,但不管怎样,“CompleteDate”总是= NON-Null值。所以我不明白这是怎么回事。
这是我的VB.NET查询:
commandstring = "SELECT Batch_Records.Part_Number, Batch_Records.Lot_Number, Batch_Records.Date_Received, " & _
"IsNull([Date_Completed], [Review_Date]) AS [CompleteDate], Batch_Records.Error, " & _
"Batch_Records.[Group], Batch_Records.MFG, Batch_Records.MFG2, Batch_Records.QC, Batch_Records.QC2, " & _
"QC_CODES.CODE_DESC, DATEADD(DD, 1 - DATEPART(DW, Batch_Records.Date_Received), Batch_Records.Date_Received) AS SundayDate " & _
"FROM EXCEL.Batch_Records LEFT JOIN EXCEL.QC_CODES ON Batch_Records.Part_Number = QC_CODES.CODE_ID " & _
"WHERE (Batch_Records.[Group]" & TheGroup & " AND Batch_Records.Date_Received > '" & FirstWeek & "' AND Batch_Records.Date_Received < dateadd(Day, 1, '" & LastWeek & "'))" & _
"ORDER BY Batch_Records.Date_Received"
当我在上面的导致错误的行上方添加此行时,我的报告会在这几个月内超时。那该怎么办?
If Not dRow("CompleteDate") Is System.DBNull.Value Then
答案 0 :(得分:4)
使用dRow.IsNull(“CompleteDate”)检查null。
或者,如果“应该”不可能,请将查询更改为永远不会返回可以为null的行。
答案 1 :(得分:0)
我使用sub(每个数据类型不同)从Datareader获取数据,但使用索引而不是名称:
#If Access Then
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Friend Function GetDbStringValue(ByVal Dr As OleDbDataReader, ByVal nr As Integer) As String
#Else
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Friend Function GetDbStringValue(ByVal Dr As MySqlDataReader, ByVal nr As Integer) As String
#End If
If IsDBNull(Dr.Item(nr)) Then
Return ""
Else
Return Dr.GetString(nr).TrimEnd
End If
End Function