I am using LINQ and have a few properties thats DateTime? type.
If i now want to add the value from a textbox i cant seem to get this to work.
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_ScoringLastUpgrade", DbType="Date")]
public System.Nullable<System.DateTime> ScoringLastUpgrade
The textbox i use i have made sure with javascript that the format will be ‘2011-06-17’
But now when i try to do this:
myObject.ScoringLastUpgrade = Convert.ToDateTime(txtScoringUpgradeDate.Text).ToShortDateString();
I get this error: “Cannot convert type string to DateTime?”
How to do this?
Don’t convert it to string using ‘ToShortDateTimeString’, just set the result of
Convert.ToDateTime:Assuming you’ve done sufficient validation on
txtScoringUpgradeDate.Text?My preference when dealing with these type conversions is to use the
TryParsemethod, e.g.:The
Convert.ToDateTime, much like the explicitDateTime.Parsewill throw anInvalidCastExceptionwhen an excepional value occurs. It’s better to make your code fault tollerant then needlesly catch an exception.UPDATE: based on your last comment:
You shouldn’t return
DateTime.MinValuein this case, asMinValueis less than the supported min value of adatetimecolumn. the CLRDateTimesupports a date range down to 0000-01-01, whereas the SQLdatetime(as well as the comparative CLRSqlDateTimetype) supports a minimum value of 1753-01-01. As it as a nullableDateTime, you should set it to null: