Click here to Skip to main content
15,881,424 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have class person.In that death date field is present.Sometimes it is null.so when i getting it from database i want to assign null value to it.
e.g. objperson._deathdate = ?. i want to assign null value to it. What can i do?
Posted

If your database field definition allows nulls for the Death date, then when you read it back, it will come back as System.DBNull
Check for this when you read the databse row, and assign null to your DateTime variable.
C#
objperson._deathdate = null;



If it doesn't, then for living people assign a default death date, which could be:
1) Far in the past
2) Same as the Birth date
3) Far in the future
You can then check for this and assign a null instead.

By preference, allow a null in the database field definition for all fields which are optional, such as the death date.

I just realised that it may not be the database side that is giving you problems.

Have you declared your DateTime as a nullable type? If not, then you can never assign a true null to it.
If not, then declare it as:
DateTime? _deathdate;
and the assignment of null will work.

[edit]Added nullable type info - OriginalGriff[/edit]
 
Share this answer
 
v3
Comments
Sergey Alexandrovich Kryukov 6-Mar-11 4:35am    
The is the only correct answer is with nullable. I just answered the same way a similar Question: http://www.codeproject.com/Answers/165259/Want-to-pass-null-value-for-Datetime.aspx.
There is a popular tradition to use DataTime.MinValue. To me, this is a pure fraud.
5 for your answer.
--SA
CS2011 6-Mar-11 6:18am    
Nice answer 5 for this
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 6-Mar-11 4:37am    
Only the first reference provide correct Answer, my 4.
See my comment to Griff's answer and referenced Answer.
--SA
Monjurul Habib 6-Mar-11 4:57am    
thank you to correct me.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900