Compare DateTime null value in SQL and in C#

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-

  • ASP.NET Web Application Administration Security section: Unable to connect to SQL Server DB
  • Strange “The ConnectionString property has not been initialized.” Error
  • How to make stored procedure into a drop down list C# MVC 5
  • Altering user-defined table types in SQL Server
  • Insert a varchar column value into another varchar column after few desired words
  • Database clients: how to wait for database activation after SQL Server restart?
  • join d in Data.AsEnumerable()
                        on p.Field<String>("EMPLID") equals
     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#.

  • Retrieve corresponding foreign key with drop-down list (WCF) C#
  • How do I lock just the relevant rows in a .NET transaction
  • Using clock ticks as random number seed
  • T-SQL to Linq: converting the having datediff in a group by
  • SQL: Nested query does not have appropriate key
  • Network related error while deploying a window application & used database to another pc …
  • 2 Solutions collect form web for “Compare DateTime null value in SQL and in C#”

    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?)


    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;
    MS SQL Server is a Microsoft SQL Database product, include sql server standard, sql server management studio, sql server express and so on.