我正在尝试从日期格式字符串执行 DateTime.TryParse
到我作为 DataView
表的一部分创建的新列。当代码运行从类型“DBNull”到类型“Date”的转换无效时,我收到此错误。
这是代码行:
DateTime.TryParse(dr("IX_ArticleStartDate"), dr("nStartDate"))
这些是我的 watch 出错时的值。
+ dr("IX_ArticleStartDate") "2015/3/11" {String} Object
+ dr("nStartDate") {} Object
我的印象是,如果 TryParse
无法转换数据类型,它将返回 NULL
值。我是否应该做一些不同的事情来将此字符串转换为 DateTime
数据类型?
dr 被实例化为 DataRow
Dim dr As DataRow = dv0.Table.Rows(i)
最佳答案
VB 隐式尝试将 DBNull 值转换为 DateTime,因为 DateTime.TryParse 的方法签名为
Public Shared Function TryParse(s As String, ByRef result As Date) As Boolean
失败了。您可以使用变量来代替:
dim startDate as DateTime
If DateTime.TryParse(dr("IX_ArticleStartDate").ToString(), startDate) Then
dr("startDate") = startDate
End If
关于vb.net - 从类型 'DBNull' 到类型 'Date' 的转换在 tryparse 上无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29392499/