Reputation: 969
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());
}
Upvotes: 0
Views: 34260
Reputation: 6050
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
Upvotes: 2
Reputation: 38488
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);
Upvotes: 3
Reputation: 1755
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());
}
Upvotes: 0
Reputation: 6425
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.
Upvotes: 3