I'm pulling data from a database (1 record) and putting each value in a textbox or dropdownlist. Some of these values are DB.null. If they are, I convert each of them to "" (blank). However, once the user has modified the textboxes/dropdown list, they can "Save" the new results. My problem is this:
If the user leaves something blank, I want to be able to maintain that the value is DB.null. Is there a way to do this?
Also, is it possible that if there is a value in a textbox and the user decides to delete it, I can also convert it to DB.Null? Here's what I tried to do to give you guys some idea:
productName != ""
? myCommand.Parameters.AddWithValue("@ProductName", productName)
: myCommand.Parameters.AddWithValue("@ProductName", DBNull.Value);
With SQL Server I believe you can interchangably use null
or DBNull.Value
to set a value to NULL
.
I'd also change your code to this:
myCommand.Parameters.AddWithValue(
"@ProductName",
// this requires a cast as ?: must return the same type
String.IsNullOrWhiteSpace(productName)
? (object)DBNull.Value
: (object)productName
);
Or using null
and without an explicit cast:
myCommand.Parameters.AddWithValue(
"@ProductName",
! String.IsNullOrWhiteSpace(productName) ? productName : null
);