Wednesday, August 27, 2008

ADO.NET C# common error dealing with inserting NULL value

If you are using c# and you are trying to insert null value into a table by using a shorthand something like below

param.Add("@abc", strAbc == "" ? null : strAbc);

it will not work. And you will got this error such as below:
Parameterized Query '(@Type nvarchar(2),@GroupType nvarchar(1),@Keyword' expects parameter @Type, which was not supplied.

To solve this problem you need to do a trick something like this
param.Add("@abc", strAbc == "" ? (object)DBNull.Value : strAbc);


change from null to (object)DBNull.Value

However, in VB.NET you do not need to cast.

2 comments:

Anonymous said...

Thanks a lot for this info, it saved me tons of work and time. Appreciate it.

Carso Leong said...

Great!