locked
Allow Empty DateTime Field RRS feed

  • Question

  • I am Developing a List Event reciever for a list

    and I want to validate the Field of DateTime is not Null ,

    It gives me an error message when I check it like this :

    if ((DateTime)properties.ListItem["DateField"] != null) 
    
    

    How to check if the Field is null ??


    thank u for help
    Monday, January 16, 2012 5:01 PM

Answers


  • Try like below
    if (String.IsNullOrEmpty(properties.ListItem["DateField"].ToString()))
    

    or simply try

    if(properties.ListItem["DateField"] == null)

     

     


    Monday, January 16, 2012 5:19 PM

All replies

  • Hello Tareq,

     

    Do not cast the field. That is:

    if (properties.ListItem["DateField"] != null && !string.IsNullOrEmpty(properties.ListItem["DateField"].ToString())

    {

        DateTime dtDateField;

        if (DateTime.TryParse(properties.ListItem["DateField"].ToString(), out dtDateField))

        {

            // go

        }

    }

     

    HTH,

     

    Chris

    Monday, January 16, 2012 5:11 PM

  • Try like below
    if (String.IsNullOrEmpty(properties.ListItem["DateField"].ToString()))
    

    or simply try

    if(properties.ListItem["DateField"] == null)

     

     


    Monday, January 16, 2012 5:19 PM
  • Thats it .., Thanks very much ..,
    thank u for help
    Monday, January 16, 2012 5:21 PM
  • Check this

     

    if (properties.ListItem["DateField"] != null) 
    
    



    Regards,
    Milan Chauhan
    Monday, January 16, 2012 5:30 PM
  • @ Geetanjali 

    if (String.IsNullOrEmpty(properties.ListItem["DateField"].ToString()))

    That code will throw a null pointer exception of 'DateField' is null as you're executing a method of that class.

     

    As for the underlying reason for the error.  The object is of type "DateTime?", not "DateTime".  "DateTime?" is the nullable version of the DateTime class, which is why the value can be null in the first place.  By casting it to the non-nullabe type (which will throw a cast exception if the value is actually null) you can't check if it's null because the compiler already knows that it can't be null.

    Monday, January 16, 2012 6:15 PM