We have a block of code that creates a list of sqlParameters and then passes them to the stored procedure. A requirement came in to conditionally null a few of the values based on whether or not the input textbox is blank.
Base code:
var SqlParams = new List<SqlParameter> {
new SqlParameter("@SomeFloat", SqlDbType.FLoat) {Value = f},
....
}
I tried a few variations on something, but it didn’t work and VS gives an error about no implicit conversion between float and null.
new SqlParameter("@SomeFloat", SqlDbType.Float) {Value = (!string.IsNullOrEmpty(tb.Text) ? double.Parse(tb.Text) : DBNull.Value)},
Is there a way to do this maintaining the list of parameters so that we dont have to rewrite the whole module?
Thanks
You’re almost there, you just have to make sure the conditional operator knows what its result should be. Cast one of the
double.ParseorDBNull.ValuetoobjectI’ve also removed some brackets and swapped the condition to make it easier to remove.
However I would normally do something like this
And not specify the value if the textbox is blank and let the stored procedure handle that case.