1

I am trying to use compare dates in a query. I have d and p are rows selected from different datatables.I want to retrieve fields from datatables based on condition. I have below conditions but throwing an error when any one of the below date is Null or empty.

I tried below statements-

join d in Data.AsEnumerable()
                    on p.Field<String>("EMPLID") equals
                    d.Field<String>("EMPLID")
 where (Convert.ToString(d.Field<DateTime>("CONTRACT_START"))!=null) &&  (Convert.ToString(d.Field<DateTime>("SIGNED_DT"))!=null) && (Convert.ToString(d.Field<String>("ACT_DT"))!=null)

Throwing an error- Can not cast DBNull.Value to Sysytem .date Time . Please use a nullable types.

when above condition is true( values are not null then I want to exceute below statement in a query)

 where (d.Field<DateTime>("CONTRACT_START") >= sd && d.Field<DateTime>("CONTRACT_START") <= ed) ||Convert.ToString(d.Field<DateTime>("SIGNED_DT"))!=" " && d.Field<DateTime>("SIGNED_DT") > d.Field<DateTime>("CONTRACT_START") || d.Field<DateTime>("ACT_DT") > d.Field<DateTime>("CONTRACT_START"))

How to check if the values are not null then execute the condition using in a query in C#.

2 Answers 2

1

Yes, that's cause your value is null in your datatable. You should change the line in your where condition to be (notice the nullable DateTime DateTime?)

(Convert.ToString(d.Field<DateTime?>("CONTRACT_START"))!=null)
Sign up to request clarification or add additional context in comments.

5 Comments

I tried this but still getting an errorjoin d in Data.AsEnumerable() on p.Field<String>("EMPLID") equals d.Field<String>("EMPLID")
(Convert.ToString(d.Field<DateTime?>("CONTRACT_START"))!=null && (Convert.ToString(d.Field<DateTime?>("SIGNED_DT"))!=null) && (Convert.ToString(d.Field<DateTime?>("GRANTACT_DT"))!=null)) where (d.Field<DateTime?>("CONTRACT_START") >= sd && d.Field<DateTime?>("CONTRACT_START") <= ed) || (d.Field<DateTime?>("SIGNED_DT") > hcmd.Field<DateTime?>("CONTRACT_START")
Can not cast DBNull.Value to System.DateTime
Is there any way we can add 1/1/1900 date value if it is null and then check if that date is > sd in query itself.
It worked i am not getting any errors . But just want to understand whow exactly < DateTime? > is checking null value in (Convert.ToString(d.Field<DateTime?>("CONTRACT_START"))!=null)
1

I'm not proficient in MySql, but you are definately using DateTime the wrong way. In c# DateTime is struct, which means it cannot be null.

You have to use Nullable dates in your c# project instead (MSDN: Using Nullable Types):

DateTime? dateTime;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.