1

I am trying to insert NULL value into a column type 'int'. I am using the following function but still I am getting InvalidOperationException. Here is my code. Please suggest.

p.type_id value is "null".

cmd.Parameters.AddWithValue("@type_id", ToNullableInt32(p.type_id))

    public static int ToNullableInt32(string s)
    {
        int i;
        if (Int32.TryParse(s, out i)) return i;
        return null;
    }
nav100
  • 2,923
  • 19
  • 51
  • 89
  • 10
    Your return type should be a nullable int: `int?`. – Jeroen Vannevel Mar 27 '14 at 18:40
  • 2
    Your `ToNullableInt32` method shouldn't even compile so I'm a little confused as to how you're getting to an `InvalidOperationException`. – Craig W. Mar 27 '14 at 18:45
  • I tried with int? but still I am getting error message. It works only if I use DBNull.value. cmd.Parameters.AddWithValue("@type_id", DBNull.Value) – nav100 Mar 27 '14 at 18:47
  • I updated my answer to include a possible solution to that as well. – Bill Mar 27 '14 at 19:03
  • possible duplicate of [Convert string to nullable type (int, double, etc...)](http://stackoverflow.com/questions/773078/convert-string-to-nullable-type-int-double-etc) – Nathan Koop Mar 27 '14 at 19:24

2 Answers2

3

Try:

 public static int? ToNullableInt32(string s)
{
    int i;
    return (Int32.TryParse(s, out i)) ? i : null;
}

EDIT: I noticed your comment to your original question about it only working with DBNull values. In that case, try adding...

cmd.Parameters.AddWithValue("@type_id", ToNullableInt32(p.type_id) ?? DBNull.Value)

...in addition to the ToNullableInt32 method update.

Bill
  • 1,431
  • 10
  • 13
2

It should be a nullable int

public static int? ToNullableInt32(string s) 
{
   ...
}
Nathan Koop
  • 24,803
  • 25
  • 90
  • 125