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());
}
1
  • add "?". DateTime ? currentDateTime; Commented Nov 24, 2011 at 9:57

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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);

2 Comments

datetimeStyle.None is the error any namespaces are added pls give me some idea
DateTimeStyles enum is in System.Globalization namespace if that's what you are asking. You should also check DateTime formats here
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

Comments

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());
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.