Reputation: 1070
I am attempting to do a DateTime.TryParse
from a date-formatted string, to a new column that I created as part of a DataView
table. I am getting this error when the code runs Conversion from type 'DBNull' to type 'Date' is not valid.
This is the line of code:
DateTime.TryParse(dr("IX_ArticleStartDate"), dr("nStartDate"))
And these are the values in my watch when it errors out.
+ dr("IX_ArticleStartDate") "2015/3/11" {String} Object
+ dr("nStartDate") {} Object
I was under the impression that a TryParse
would return a NULL
value if it fails to convert datatypes. Is there something that I should be doing different to convert this string to a DateTime
datatype?
dr is instantiated as a DataRow
Dim dr As DataRow = dv0.Table.Rows(i)
Upvotes: 2
Views: 3665
Reputation: 35318
A DateTime
is a value type and cannot have a null value. You can do something like this:
Dim result As DateTime
Dim myDate As DateTime? = If(Not dr.IsNull("IX_ArticleStartDate") AndAlso _
DateTime.TryParse(dr.IsNull("IX_ArticleStartDate").ToString(), result), _
result, New DateTime?)
In this example, the variable myDate
is not actually a DateTime
, it's a Nullable(Of DateTime)
as indicated by the question mark ?
after DateTime
in the declaration (see MSDN). The TryParse
method actually takes a string
value as the first argument and an output parameter which is a DateTime
value as the second argument. If the parse is successful, it returns True
and sets the output parameter to the parsed DateTime
value; on the other hand, if the parse is not successful, it returns False
and sets the output parameter to DateTime.MinDate
which is not very useful because it's difficult to distinguish between a valid use of DateTime.MinDate
and null.
The example makes use of a ternary operator which either parses and returns the date value, if it's not null, or else returns a nullable date instead (New DateTime?
).
You would then use myDate.HasValue()
accordingly to determine if the value is null, and if it's not null, you can use its value: myDate.Value
.
Upvotes: 2
Reputation: 31743
VB implicitly try's to cast the DBNull Value to DateTime, since the method signature of DateTime.TryParse is
Public Shared Function TryParse(s As String, ByRef result As Date) As Boolean
which fails. You can use a variable instead:
dim startDate as DateTime
If DateTime.TryParse(dr("IX_ArticleStartDate").ToString(), startDate) Then
dr("startDate") = startDate
End If
Upvotes: 2