Testing SqlCommand.Parameters["@Name"].Value == null

  • Thread starter Thread starter Giammarco
  • Start date Start date
G

Giammarco

Hi all,
I have the following code:

int? name;

SqlCommand.Parameters.AddWithValue("@Name", name);

if (SqlCommand.Parameters["@Name"].Value == null)
{
SqlCommand.Parameters["@Name"].Value = DBNull.Value;
}

Well, I do not assign any value to 'name', so it's value is null, as it
is a nullable type. However, when I check if
SqlCommand.Parameters["@Name"].Value == null, the condition is not
satisfied.

Any clue why the condition is not satisfied?

Thanks,
Giammarco
 
You must use a different strategy when checking for NULL.

If IsDBNull(<your object to test>) ...


--
____________________________________
William (Bill) Vaughn
Author, Mentor, Consultant
Microsoft MVP
www.betav.com/blog/billva
www.betav.com
www.sqlreportingservices.net
Please reply only to the newsgroup so that others can benefit.
This posting is provided "AS IS" with no warranties, and confers no rights.
__________________________________
 
Just an update on this issue. I've solved the problem in the following
way:

if (sqlCmd.Parameters["@PersonSex"].Value is INullableValue)
{
INullableValue INullableParam =
(INullableValue)sqlCmd.Parameters["@Name"].Value;

if (!INullableParam.HasValue)
{
sqlCmd.Parameters["@Name"].Value = DBNull.Value;
}
}

Reagards,
Giammarco Schisani
 
If you are using INullableValue, you must be using V2.0 Beta2. That
interface has been removed in the final version of V2.0.

Your original solution will work in the end because boxing (casting to
object) of Nullable<T> removes the nullable and becomes either null or
(object)T;

Nullable<int> x = 3, y = null;
Console.WriteLine("{0} {1}", ((object)x),((object) y)??"null");

For the DataSet, its usefull to do this kind of thing
datarow[0] = ((object)value) ?? DBNull.Value; // ?? is new C# 2.0 syntax.
 
Back
Top