handle null from database
I need to round and print a price like below, but this does not handle null values.
How can I handle null values on one line of code? DBRSet is an SQLDataReader and the price is money type in SQL.<%= Math.Round(DBRSet("price"))%>
I have about 200 .aspx pages of this so I could also use some tips on how to change these in an easy way? Can I do a search and replace w开发者_如何学编程ith a reg-exp or something like that?
You have to handle the DbNull
case explicitly, for example:
<%= DbNull.Equals(DBRSet["price"]) ? "null" : Math.Round(DBRSet["price"]).ToString() %>
This is unwieldy, so it makes sense to have a helper method something like this somewhere:
static class FormatDbValue {
public static string Money(object value)
{
if (DbNull.Equals(value)) {
return "0";
}
return Math.Round((decimal)value);
}
}
Which would allow
<%= FormatDbValue.Money(DBRSet["price"]) %>
Of course finding and changing all such code to use the helper method would be... unpleasant. I would do it by searching throughout the project (maybe in smaller chunks of the project) for something indicative (maybe Math.Round
?) and review it manually before replacing.
If you don't want to change the aspx's, but can easily change the definition of the DBRSet
property, you can put there a wrapper over the SqlDataReader
and implement your own indexer that would first check for null and go into the inner dataReader
to get the value if not null.
精彩评论