简体   繁体   中英

How to assign DBNull to a primitive type to facilitate Database insert

I have the following line in my code assigning a value to a datatable column. It could be null or a price.

double? Price;
price = range.Cells[i, j].Value2 == null ? Double.NaN : range.Cells[i,j].Value2;
row["Price"] = **(price != Double.NaN) ? price.Value** : (object)DBNull.Value;

VS 2010 produces a green squiggly line (the code within the pairs of stars) saying

The expression type is always false since double can never be null

How can I get around this so that I can assign null for price in the database table if need be?

Using Double.NaN won't help you because NaN is not equal even to itself. It's not clear why you're doing this in two stages though - I'd suggest just:

row["Price"] = range.Cells[i, j].Value2 ?? (object) DBNull.Value;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM