Reputation: 11019
Can anyone see from the following function why I would be getting an "Invalid Cast Exception"? More specifically this is the error "Conversion from string "yyyyMMdd" to type 'Integer' is not valid."
I am trying to convert a DateTime value from the database to a String with the format "yyyyMMdd" so for example October 22, 1985 would be "19851022".
dbReader(fieldName).ToString("yyyyMMdd")
Here is the entire function ...
Private Function GetDBReaderDateValue(ByVal dbReader As IDataReader, ByVal fieldName As String) As String
If dbReader(fieldName) Is DBNull.Value Then
Return ""
Else
Return dbReader(fieldName).ToString("yyyyMMdd")
End If
End Function
Upvotes: 1
Views: 2157
Reputation: 460288
If fieldName
is not a DateTime, conversion will fail. Try to cast it to a Datetime first:
Dim dt As Date
If Date.TryParse(dbReader(fieldName).tostring, dt) Then
Return dt.ToString("yyyyMMdd")
Else
Throw New ArgumentException("GetDBReaderDateValue needs a Date-Column as parameter!")
End If
Upvotes: 1
Reputation: 210755
It seems like you're calling ToString
on an Object
... and there's no overload that takes a String
parameter. You probably need to cast to a DateTime
first.
Upvotes: 1