0

How to pass the null value to datetime datatype in asp.net?

cmdInsertUpdateConsultantDetails.Parameters.Add("@DateofExpiry", SqlDbType.DateTime);
if (txtdateofexpiry.Text.Trim() == "")
{
    cmdInsertUpdateConsultantDetails.Parameters["@DateofExpiry"].Value =
}
else
{
    cmdInsertUpdateConsultantDetails.Parameters["@DateofExpiry"].Value = 
        Convert.ToDateTime(txtdateofexpiry.Text.Trim());
}
Avo Muromägi
  • 1,563
  • 1
  • 12
  • 21
hmk
  • 969
  • 10
  • 38
  • 70

4 Answers4

3

DateTime is a value type, it cannot be null. You can use Nullable<DateTime> (or the syntax shortform DateTime?) instead of that.

Here's an example:

DateTime? dateTime;
DateTime.TryParseExact(txtdateofexpiry.Text.Trim(), "dd/MM/yyyy", null, DateTimeStyles.None, out dateTime);
Ufuk Hacıoğulları
  • 37,978
  • 12
  • 114
  • 156
  • datetimeStyle.None is the error any namespaces are added pls give me some idea – hmk Nov 24 '11 at 09:53
  • DateTimeStyles enum is in System.Globalization namespace if that's what you are asking. You should also check [DateTime formats here](http://www.csharp-examples.net/string-format-datetime/) – Ufuk Hacıoğulları Nov 24 '11 at 10:47
3

DateTime is not a nullable type. If you don't supply a value it's equal to DateTime.MinValue

You can use

DateTime? MyNullableDateTime;

This question has more detail in the answer, if you are interested.

Community
  • 1
  • 1
Neil Thompson
  • 6,356
  • 2
  • 30
  • 53
2

Simple here you can give DbNull.Value to pass NULL value.

if (txtdateofexpiry.Text.Trim() == "")
{
    cmdInsertUpdateConsultantDetails.Parameters["@DateofExpiry"].Value = DbNull.Value
}

It's also recommended the use of DateTime? or Nullable

Sreekumar P
  • 5,900
  • 11
  • 57
  • 82
0

you can pass it as DBNull.Value. So it would be

cmdInsertUpdateConsultantDetails.Parameters.Add("@DateofExpiry", SqlDbType.DateTime);
if (txtdateofexpiry.Text.Trim() == "")
{
    cmdInsertUpdateConsultantDetails.Parameters["@DateofExpiry"].Value = DBNull.Value;
}
else
{
    cmdInsertUpdateConsultantDetails.Parameters["@DateofExpiry"].Value = 
          Convert.ToDateTime(txtdateofexpiry.Text.Trim());
}
Junaid
  • 1,708
  • 16
  • 25