Problems with nullable DateTime

B

Bill Gower

Why won't this work? What do I need to do to make it work?

DateTime? DateMember;

if((DateTime.Parse(oldRow["datemember"].ToString) == null))
DateMember = null;
else
DateMember = DateTime.Parse(oldRow["datemember"].ToString());

The program is failing on the if saying that the null value in the field in
the table is not able to be represented as a string. Which is fine, I can
understand that, so how do I check for a field in a table for null and
assign either a null to a local variable to the field value.


Bill
 
Q

Quoc Linh

Why won't this work? What do I need to do to make it work?

DateTime? DateMember;

if((DateTime.Parse(oldRow["datemember"].ToString) == null))
DateMember = null;
else
DateMember = DateTime.Parse(oldRow["datemember"].ToString());

The program is failing on the if saying that the null value in the field in
the table is not able to be represented as a string. Which is fine, I can
understand that, so how do I check for a field in a table for null and
assign either a null to a local variable to the field value.

Bill

The above won't work because: oldRow["datemember"].ToString() will
fail if oldRow["datemember"] is null.

Test for if your datetime field equals to DBNull.Value:

if (oldRow["datemember"] != DBNull.Value)
DateMember = DateTime.Parse(oldRow["datemember"].ToString());
else
DateMember = DateTime.MinValue; //You cannot assign a DateTime
value to null

One liner:
DateMember = oldRow["datemember"] == DBNull.Value ?
DateTime.MinValue :
DateTime.Parse(oldRow["datemember"].ToString());

Have fun.

Quoc Linh
 
J

Jon Skeet [C# MVP]

Bill Gower said:
Why won't this work? What do I need to do to make it work?

DateTime? DateMember;

if((DateTime.Parse(oldRow["datemember"].ToString) == null))
DateMember = null;
else
DateMember = DateTime.Parse(oldRow["datemember"].ToString());

Well, that's not your actual code - ToString is a method, not a
property. In future, it would be helpful to post the actual code.
The program is failing on the if saying that the null value in the field in
the table is not able to be represented as a string. Which is fine, I can
understand that, so how do I check for a field in a table for null and
assign either a null to a local variable to the field value.

You should examine the value of oldRow["datemember"] *before* trying to
parse it, instead of after.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Assigning null value to DateTime 2
SqlDateTime and DateTime 2
Question about DateTime 3
Nullable Dates 3
Why no nullable var objects? 15
Nullable class 2
How to... 1
need to assign null 3

Top