Reputation: 3071
I have int? type value which can be either null or have some value. I want to execute a insert statement using parametrized query to insert accordingly.
int? val1=null;
SqlCeCommand cmd;
string insert = "insert into table(col1)values(@col_1)";
cmd = new SqlCeCommand();
cmd.CommandText = insert;
cmd.Parameters.AddWithValue("@col_1", val1 ?? Convert.ToInt32(DBNull.Value)));
cmd.Connection = cn1;
cn1.Open();
cmd.ExecuteNonQuery();
cn1.Close();
This code throws format exception error. I even tried
cmd.Parameters.AddWithValue("@col_1", (!val1.HasValue) ? val1 : Convert.ToInt32(DBNull.Value));
How shld it b done?
Upvotes: 0
Views: 7675
Reputation: 36320
I would believe that changing the line to the following should work:
cmd.Parameters.AddWithValue("@col_1", val1 ?? DBNull.Value);
Since this would set the parameter value to an object type.
If that fails for some reason try to cast the result to an object like this:
cmd.Parameters.AddWithValue("@col_1", (object)(val1 ?? DBNull.Value));
But this should not be necessary.
Edit: Actually, this should work:
cmd.Parameters.AddWithValue("@col_1", val1 ?? (object)DBNull.Value);
Upvotes: 1
Reputation: 1620
You Should change add parameter code like this:
if (val1.HasValue)
{
cmd.Parameters.AddWithValue("@col_1", val1.Value);
}
else
{
cmd.Parameters.AddWithValue("@col_1", DBNull.Value);
}
Upvotes: 0
Reputation: 63065
no need to convert if null set DBNull
cmd.Parameters.AddWithValue("@col_1", (object)val1 ??DBNull.Value);
Upvotes: 1