Reputation: 1489
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
Upvotes: 2
Views: 1365
Reputation: 11317
This is a good case for an extension:
public static object TryParseSqlValue(this object input)
{
if (null == input)
return DBNull.Value;
if (input.GetType() == typeof(string) && input.ToString() == string.Empty)
return DBNull.Value;
else
return input;
}
myTextBox.Text.TryParseSqlValue(); // returns either the non-empty
// string or DBNull.Value
You can modify it for other datatypes...
Upvotes: 1
Reputation: 46595
You're almost there, you just have to make sure the conditional operator knows what its result should be. Cast one of the double.Parse
or DBNull.Value
to object
I've also removed some brackets and swapped the condition to make it easier to remove.
new SqlParameter("@SomeFloat", SqlDbType.Float)
{
Value = string.IsNullOrEmpty(tb.Text)
? DBNull.Value
: (object)double.Parse(tb.Text)
}
However I would normally do something like this
if (!string.IsNullOrEmpty(tb.Text))
command.Parameters.AddWithValue("@SomeFloat", double.Parse(tb.Text));
And not specify the value if the textbox is blank and let the stored procedure handle that case.
Upvotes: 4
Reputation: 857
I would totally recommend to point each call to a method and let it decide the value that's going to be passed as a parameter.
Upvotes: 1