sam
sam

Reputation: 2606

Error while passing DBNull to SqlParameter

I am trying to pass null value to SqlParameter if the value of variable vName is null, else pass vName value as shown below

cmd.Parameters.Add(new SqlParameter("@NAME", SqlDbType.VarChar)).Value = vName ? null : DBNull.Value;

but I get an error

Cannot implicitly convert type 'string' to 'bool'

I searched and found that I have to use AgeItem.AgeIndex but I got error that says

The name 'AgeItem' does not exist in the current context

cmd.Parameters.Add(new SqlParameter("@NAME", SqlDbType.VarChar)).Value =(object)AgeItem.AgeIndex ?? DBNull.Value;

Upvotes: 1

Views: 736

Answers (3)

John
John

Reputation: 829

IMHO much cleaner:

if (vName != null)
    cmd.Parameters.AddWithValue("@NAME",vName);
else
    cmd.Parameters.AddWithValue("@Name",null);

Upvotes: 1

Malitha Shan
Malitha Shan

Reputation: 21

Code should be change as follow

cmd.Parameters.Add(new SqlParameter("@NAME", SqlDbType.VarChar)).Value!= null ? vName: DBNull.Value;

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460128

vName is a string but you use it like it was a bool: vName ? .... Use vName == null ? ...:

cmd.Parameters.Add(new SqlParameter("@NAME", SqlDbType.VarChar)).Value =
     vName == null ? DBNull.Value : (Object)vName;

Upvotes: 3

Related Questions