Anwar
Anwar

Reputation: 4246

Default value SqlCommand.Parameters.Add C# Issue

I have a program that connect to a database, use a stored procedure to insert a line in a table, and close the connection. Everything works ok instead of the line below.

VisualStudio underline in red the last line :

string value = textBox_value.Text;

command.Parameters.Add(new SqlParameter("@value", (String.IsNullOrEmpty(value)) ? DBNull.Value : value));

Error message :

There is no explicit conversion between 'System.DBNull' and 'string'

String.IsNullOrEmpty(value) returns true if the value is empty, else returns false.

I found the solution by writting this enourmous line of code :

if (String.IsNullOrWhiteSpace(value)) 
{
        command.Parameters.Add(new SqlParameter("@value", DBNull.Value));
}
else 
{
        command.Parameters.Add(new SqlParameter("@value", CT_Intitule));
}

But is that normal we can't perform a one-line condition ?

EDIT

Thanks to Rahul Singh, that pointed the MSDN documentation in which the function is described as expecting 2 same type, I resolved my issue doing this :

command.Parameters.Add
(
    ( String.IsNullOrWhiteSpace(value) ) ? 
        new SqlParameter("@value", CT_Intitule) 
        : 
        new SqlParameter("@value", DBNull.Value)
); 

Upvotes: 0

Views: 1412

Answers (2)

Steve
Steve

Reputation: 216303

You could fix you code casting the DBNull.Value to object

command.Parameters.Add(new SqlParameter("@value", 
                     string.IsNullOrEmpty(value) 
                     ? (object)DBNull.Value
                     : CT_Intitule);

But I wish to discourage the usage of the overload that pass directly the value.
It is always better and more error safe to always specify the parameter type

command.Parameters.Add(new SqlParameter("@value", SqlDbType.NVarChar)).Value =
                     string.IsNullOrEmpty(value) 
                     ? (object)DBNull.Value
                     : CT_Intitule;

You could read more about the effects of the C# code on database performances here

How Data Access Code Affects Database Performance

Upvotes: 1

Rahul Singh
Rahul Singh

Reputation: 21795

According to MSDN:-

Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.

Conditional Operator expects both types to be same, for example you cannot do:-

string test = 1 == 1 ? "True" : 5;

It will throw the same error because there is no implicit conversion possible between a string ("True") and int (5).

Upvotes: 1

Related Questions