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)
);
?:operator since it's expressions have to convert to each other an implicit way at least..? :condition expect the two parameters to be the same type. I didn't get this before.