Reputation: 195
In the web app I'm working on, the web app should be able to accept null DateTime
values, because customers might be hesitant to give information about their Date of Birth. Of course, this won't be an easy task, because in C#, DateTime
is not nullable.
DateTime rawBirthDate = Convert.ToDateTime(txtDOB.Text);
fxTxn.BirthDate = rawBirthDate;
with that, I had to change my code to accept a null value:
DateTime? rawBirthDate = string.IsNullOrEmpty(txtBirthDate) ? (DateTime?)null : DateTime.Parse(txtBirthDate);
fxTxn.BirthDate = Convert.ToDateTime(rawBirthDate);
this code, in turn, returns 1/1/0001 12:00:00.000 AM
. However, MSSQL throws a DateOutOfRangeException
, saying the date must be between 1/1/1753 and 12/31/9999.
I'm completely stuck in here. On my SQL table, I allowed the BirthDate
column to accept null values. Question now is, how do I make C# consider null DateTime values? The end result would be that, if the Customer did not provide Date of Birth information, the system should still be able to save the record but the BirthDate column in the customer's record would still be NULL.
Upvotes: 0
Views: 1332
Reputation: 2656
What you need to do is this: your column table should accept null for BirthDate (that's correct). In C#, make the variable rawBirthDate nullable.
Now, the condition you need to check is:
rawBirthDate.HasValue
If it's true, then insert the date in db.
If false, do not insert anything in the db (that's what 'allow null' means in SQL).
Upvotes: 3
Reputation: 6543
Why are you converting null value in datetime, if you define nullable variable then it can store null vaue. Actually you need to define BirthDate property also nullable and store null value if user have not entered date like
fxTxn.BirthDate = string.IsNullOrEmpty(txtBirthDate) ? null : DateTime.Parse(txtBirthDate);
In db you need to make that column to allow null value and check value of BirthDate like
if (fxTxn.BirthDate.HasValue)
{
// pass value in db otherwise not
}
Upvotes: 2
Reputation: 4911
I think the problem might be in the code that actually inserts the value into database:
...
var valueToInsert = rawBirthDate ?? DBNull.Value;
...
Upvotes: 2
Reputation: 9089
how do I make C# consider null DateTime values
Your value was null. The problem is that you converted it to a standard DateTime which is giving you the DateTime.MinValue
(1/1/0001)
Upvotes: 2