简体   繁体   中英

convert string null value to int

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

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.

It should be a nullable int

public static int? ToNullableInt32(string s) 
{
   ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM