简体   繁体   中英

how to convert date time if passing null value in date field

How to store null value and how to insert null values in database? im getting this error.

String was not recognized as a valid DateTime.

if (taskObj.EstimatedTime == null)
{
    taskObj.EstimatedTime = Convert.ToDateTime(estimateTimeLabel.Text);
}

public DateTime EstimatedTime
{
    set { estimatedTime = value; }
    get { return estimatedTime; }
}

You need to specify in your database that you can allow null for the specific column.

If you already have a database you can run something like:

ALTER COLUMN `YourColumn` datetime2() DEFAULT NULL

This will allow you to use null in your database.

You also need to convert your datetime in code to a Nullable type. Otherwise .NET comes out with a default date 1/1/0001 12:00:00 AM (not very helpful).

There are two ways to do this. I personally recommend the first but it's purely down to coding style.

You can do this by either using the ? operator:

 public DateTime? EstimatedTime
{
    set { estimatedTime = value; }
    get { return estimatedTime; }
}

Or by the Nullable generic function:

public Nullable<DateTime> EstimatedTime
{
    set { estimatedTime = value; }
    get { return estimatedTime; }
}

Don't forget to convert your estimatedTime field to a nullable type also (again either by using the ? operator or Nullable.

I hope that helps. If not then leave me a comment and I will do my best to assist you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM