none
how to assign a datevalue to the date varaible if it is null RRS feed

  • Question

  • Hi

    Please can you let me know how can store the value  as '31-12-2060' if the  _dateto value is null

    DateTime _dateto = Convert.ToDateTime(row1["ENDDATE"].ToString());


    polachan

    Friday, November 3, 2017 12:31 AM

All replies

  • DateTime _dateto = Convert.ToDateTime(Convert.IsDBNull(row1["ENDDATE"]) ? row1["ENDDATE"] : "2060-12-31");


    On the other hand, if your method of fetch/assign data will just assign null to the data field:

    DateTime _dateto = Convert.ToDateTime(row1["ENDDATE"] ?? "2060-12-31");


    Friday, November 3, 2017 1:20 AM
    Answerer

  • Hi polachan,

    >>Please can you let me know how can store the value  as '31-12-2060' if the  _dateto value is null

    If you declare a DateTime, then the default value is DateTime.MinValue, and hence you have to check it like this:

    DateTime datetime = new DateTime();
    
    if (datetime == DateTime.MinValue)
    {
        //unassigned
    }
    

    If you really want to support null, use DateTime? to create a nullable DateTime.

            //DateTime? _dateto = Convert.ToDateTime(row1["ENDDATE"].ToString());
                DateTime? _dateto = null;
    
                if ((!_dateto.HasValue) || ((_dateto == null)))
                {
                    //store the value  as '31-12-2060' if the  _dateto value is null
    
                    _dateto = Convert.ToDateTime("12-31-2060");
                }
    
                MessageBox.Show(_dateto.ToString());
    


    Best Regards,

    Yohann Lu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, November 6, 2017 2:12 AM
    Moderator