Shree Shree - 8 months ago 117
C# Question

DateTime.MinValue and SqlDateTime overflow

I don't want to validate

so I want to pass
in database.

My code:

if (txtBirthDate.Text == string.Empty)
objinfo.BirthDate = DateTime.MinValue;
objinfo.BirthDate = DateTime.Parse(txtBirthDate.Text);

Date = {1/1/0001 12:00:00 AM}

I got a SQL Error:

SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.

I under stand it but I don't understand why
return invalid date time which is unable to insert in database.How to handle this type of situation?


Basically, don't use DateTime.MinValue to represent a missing value. You can't use DateTime.MinValue in a SQL Server DateTime field, as SQL Server has a minimum value of the start of 1753.

Instead, make your BirthDate property a Nullable<DateTime> (aka DateTime?), and set it to null when you don't have a value. Also make sure your database field is nullable. Then you just need to make sure that that null ends up as a NULL value in the database. Exactly how you do that will depend on your data access, which you haven't told us anything about.