Click here to Skip to main content
15,912,897 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Here is my code, i was trying to pass null value if the string is empty.

But it throws exception.any one help me what am missing here ?

DateTime strDateTime = System.Convert.ToDateTime(item.TerminationDate);
string conv=System.Convert.ToString (strDateTime);
DateTime dateToSave;
dateToSave = DateTime.Parse(conv);

 if (!String.IsNullOrEmpty(conv))
     dateToSave = DateTime.Parse(conv);
else
    dateToSave= System.DBNull.Value


[edit]Code block added - OriginalGriff[/edit]
Posted
Updated 13-Mar-11 21:51pm
v2

I'm not that surprised, really.
1) You convert from a string to a DateTime:
C#
DateTime strDateTime = System.Convert.ToDateTime(item.TerminationDate);

2) You convert the DateTime back to a string:
C#
string conv=System.Convert.ToString (strDateTime);

3) You convert the string back to a DateTime:
C#
dateToSave = DateTime.Parse(conv);

4) You then test if the string you just used would have thrown an exception:
C#
if (!String.IsNullOrEmpty(conv))

5) This won't compile:
C#
dateToSave = System.DBNull.Value


Perhaps you need to think this a bit, as there are a number of problems here:

1) It could fail if the item.TerminationDate is not a valid date
2) You don't need to keep transfering between strings and DateTime.
3) You should check before you use, rather than after.
4) You can only assign DateTime values to a DateTime.

What are you actually trying to do?
 
Share this answer
 
I'd do this if I were you:
string strDateTime = item.TerminationDate.ToString();
DateTime dateToSave;
if (!string.IsNullOrEmpty(strDateTime))
{
    dateToSave = Convert.ToDateTime(strDateTime)
}

That way I wouldn't have to worry about assigning a null value to the DateTime variable. You should include the else { } construct to add code that will execute if the string variable is null.
 
Share this answer
 
v2
DateTime data types don't support DBNull values. You need to change your dateToSave to an Object, or create a Boolean flag to say if it's populated or not
 
Share this answer
 

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