26
        DbParameter param = comm.CreateParameter();
        param = comm.CreateParameter();
        param.ParameterName = "@StaffId";
        if (!string.IsNullOrEmpty(activity.StaffId))
            param.Value = activity.StaffId;
        param.DbType = DbType.String;
        comm.Parameters.Add(param);

The above does not work (obviously), object not instantiated. I am attempting to insert a NULL into the database when StaffId is NOT populated. How can I achieve this?

SkonJeet
  • 4,827
  • 4
  • 23
  • 32

4 Answers4

47

You can use DBNull.Value when you need to pass NULL as a parameter to the stored procedure.

param.Value = DBNull.Value;

Or you can use that instead of your if operator:

param.Value = !string.IsNullOrEmpty(activity.StaffId) ? activity.StaffId : (object)DBNull.Value;
Andrey Gurinov
  • 2,825
  • 1
  • 20
  • 23
  • 1
    Thanks for the edit Andrey - appreciate it. It seems crazy to have to cast this as an object though (to me anyway). – SkonJeet Mar 21 '12 at 09:56
8

Try DBNull.Value

if (!string.IsNullOrEmpty(activity.StaffId))
   param.Value = activity.StaffId;
else
  param.Value=DBNull.Value;
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
  • is there a way of using the ? operator for a sort of shorthand if else statement here?? It seems to not like the String/DBNull.Value conversion!? – SkonJeet Mar 21 '12 at 09:33
  • 1
    Try this: param.Value = !string.IsNullOrEmpty(activity.StaffId) ? activity.StaffId : (object)DBNull.Value; – Andrey Gurinov Mar 21 '12 at 09:41
4

You can always use the null-coalescing operator (??)

param.Value = activity.StaffId ?? (object)DBNull.Value;
3

You could use DBNull.Value:

param.Value = DBNull.Value;
Andomar
  • 232,371
  • 49
  • 380
  • 404