21

I have a datetime datatype : dttm

Also the database field type is datatime

Now I am doing this:

if (dttm.HasValue)
{
    cmd.Parameters.AddWithValue("@dtb", dttm);
}
else
{
    // It should insert null value into database
    // through cmd.Parameters.AddWithValue("@dtb", _____)
}

How can this be done.

Django Anonymous
  • 2,987
  • 16
  • 58
  • 106
  • 3
    From http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparametercollection.addwithvalue.aspx : The value to be added. Use DBNull.Value instead of null, to indicate a null value. – a1ex07 May 23 '13 at 14:54

3 Answers3

45

This can be done using the null-coalescing operator: if the value of dttm is null the DBNull.Value will be inserted otherwise the value of dttm will be used

cmd.Parameters.AddWithValue("@dtb", dttm ?? (object) DBNull.Value);

This will eliminate the need for the if statment

Kevin Kunderman
  • 2,036
  • 1
  • 19
  • 30
  • 1
    Yup, this is the cleanest approach. I wasn't entirely sure of the viability of casting in the second operand of the null coalescing operator, but it works fine. – Jon Skeet May 23 '13 at 14:59
21

Use DBNull.Value

if (dttm.HasValue)
{
    cmd.Parameters.AddWithValue("@dtb", dttm);
}
else
{
    cmd.Parameters.AddWithValue("@dtb", DBNull.Value)
}
Carlos Landeras
  • 11,025
  • 11
  • 56
  • 82
3

if your field allows null value;

if (dttm.HasValue)
{
    cmd.Parameters.AddWithValue("@dtb", dttm);
}
else
{
    cmd.Parameters.AddWithValue("@dtb", DBNull.Value)
}
Furkan Ekinci
  • 2,472
  • 3
  • 29
  • 39