views:

167

answers:

1

I'm trying to Parse dates entered into a TextBox into a DateTime value but I keep getting an exception in the TryParseExact method. What I'm trying to do is:

DateTime.TryParseExact(tbAddDate.Text.Trim, "yyMMdd", New CultureInfo("sv-SE"), DateTimeStyles.None, row.Date)

This throws an InvalidCastException with the message "Conversion from type 'DBNull' to type 'Date' is not valid." I realize what is happening is that it's trying to set row.Date to DBNull which is not a valid value for a DateTime. What I don't understand is why it's trying to do this, as the documentation states that it should be set to MinValue and not DBNull.

As a sidenote, I know that I can get around a lot of these problems by using a DateTimePicker but the customer feels that they are very clunky as it's not possible to enter the dates directly with the keyboard.

+1  A: 

It seems that (as magnifico's comment suggests) the problem is strictly related to the fact you're passing row.Date as the result argument. It must occur when the code attempts to assign row.Date with Date.MinValue (unless the documentation is inaccurate, which is less likely in this scenario). I'd advise that you pass some different result argument, and use its value to update row.Date after calling TryParseExact. It might not be the ultimate permanent solution, but it should help you inspect this bug and find the cause to the InvalidCast exception.

Sidenote: perhaps this row.Date doesn't accept Date.MinValue as a legitimate value, i.e.: row.Date might be willing to accept only dates from 01/01/2000 onwards, and Date.MinValue returns 01/01/0001.

M.A. Hanin
This solved the issue. row.Date belongs to a dataset and the Underlying DataColumn has DefaultValue = <DBNull> If i change the default value to 01/01/0001 it works, but I don't want to do this since that would effectively allow null values. I'll just go with what you suggested.
MatsT