Search code examples
asp.netstringcastingdbnull

DBNull to String in ASP.NET inline expressions has casting error


Hey guys, a table in my database has a field "Description" that Allow's Nulls'. This causes a problem when rendering the page in ASP.NET since I want to make sure I'm decoding the string as its coming out of the database as I'm encoding it on the way in. Naturally there are some NULL's in the Description field, which I would like to keep.

So my ASP.NET page has this code

<asp:TextBox ID="DescInfo" Text='<%# HttpUtility.HtmlDecode((string)Eval("Description")) %>' />

So when I render the page, I will get:

Unable to cast object of type 'System.DBNull' to type 'System.String'.

The way I look at it, I have two options:

  • bind during load

OR

  • make the table a non NULL table and use empty values instead

Anyone have a better idea perhaps?


Solution

  • While DBNull cannot be cast to a string, it does have a ToString() method that returns an empty string. I might do it like this:

    <%# HttpUtility.HtmlDecode(Eval("Description").ToString()) %>
    

    That way you don't have to test for DBNull or anything. String.ToString() just returns the string, and DBNull.ToString() returns an empty string. This also has the advantage of only calling Eval one time per row instead of twice. The only thing that could trip you up is if your data contains both null and DBNull (you can't call ToString on null but you can on DBNull) but I don't think that's actually possible in this case.