1

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;
2
  • md.Parameters.Add(new SqlParameter("@NAME", SqlDbType.VarChar)).Value = vName ? vName : DBNull.Value; is it a spelling mistake? u didnt pass vname Commented Oct 8, 2018 at 15:14
  • @Naruto I did not get it Commented Oct 8, 2018 at 15:47

3 Answers 3

3

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;
Sign up to request clarification or add additional context in comments.

Comments

1

IMHO much cleaner:

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

1 Comment

PS. If the command is a Stored Procedure and can accept a null value then the else and subsequent lines are not necessary.
0

Code should be change as follow

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

1 Comment

error -> Type of conditional expression cannot be determined because there is no implicit conversion between 'string' and 'System.DBNull'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.