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?
While
DBNullcannot be cast to a string, it does have aToString()method that returns an empty string. I might do it like this:That way you don’t have to test for
DBNullor anything.String.ToString()just returns the string, andDBNull.ToString()returns an empty string. This also has the advantage of only callingEvalone time per row instead of twice. The only thing that could trip you up is if your data contains bothnullandDBNull(you can’t call ToString onnullbut you can onDBNull) but I don’t think that’s actually possible in this case.