Is there a better/cleaner way to do this?
int stockvalue = 0;
if (!Convert.IsDBNull(reader[\"StockValue\"]))
stockvalue = (int)reader[\"StockValue\"];
Not really. You could encapsulate it in a method:
public int getDBIntValue(object value, int defaultValue) {
if (!Convert.IsDBNull(value)) {
return (int)value;
}
else {
return defaultValue;
}
And call it like this:
stockVaue = getDBIntVaue(reader["StockValue"], 0);
Or you could use coalesce
in your query to force the returned value to be non-null.
Edit - corrected dumb code errors based on comments received.