Niklas
Niklas

Reputation: 13135

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 with a reg-exp or something like that?

Upvotes: 1

Views: 255

Answers (2)

Jon
Jon

Reputation: 437376

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.

Upvotes: 2

František Žiačik
František Žiačik

Reputation: 7614

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.

Upvotes: 0

Related Questions