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

958 views Asked by At

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; }
}
1

There are 1 answers

0
K-Dawg On BEST ANSWER

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.