Member Avatar for lithium112

I am using Linq and keep getting a DBNull error since my datatable contains DBNulls. I have:

var Sum = (from dt in dt1.AsEnumerable()
                 where (dtCutOffDate.Subtract(dt.Field<DateTime>("Date")).Days) >= iStartRange
                 && dtCutOffDate.Subtract(dt.Field<DateTime>("Date")).Days <= iEndRange
                 && ((items == null) || (dt.Field<string>("AcctNo") == items))
                 && (dt.Field<string>("type").Contains("6") || dt.Field<string>("type").Contains("9"))
                 select dt.Field<double>("amount")).Sum();

The date column is the one that is throwing the dbnull error. Is there any way to check for dbnull? If I use where date != dbnull.value, c# will not accept the code. I have tried <datetime?> but c# still doesn't like the code. Would anyone happen to know of a solution?

Recommended Answers

All 2 Replies

Instead of

 where (dtCutOffDate.Subtract(dt.Field<DateTime>("Date")).Days) >= iStartRange
                 && dtCutOffDate.Subtract(dt.Field<DateTime>("Date")).Days <= iEndRange

Just add a '?' character.

 where (dtCutOffDate.Subtract(dt.Field<DateTime?>("Date")).Days) >= iStartRange
                 && dtCutOffDate.Subtract(dt.Field<DateTime?>("Date")).Days <= iEndRange

You should avoid the exception now.

Member Avatar for lithium112

Thanks! The ? worked.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.