How do I handle Conversion from type 'DBNull' to type 'String' is not valid

mEeRkAt picture mEeRkAt · Feb 11, 2009 · Viewed 43.8k times · Source

I need some expect advice on how to handle the following:- I have a data field misc_text_2 that is of type varchar(25) and allows NULL. Now if I use the following syntax

<asp:Label ID="lblPrinter" runat="server"  Text='<%# iif(eval("misc_text_2") is dbnull.value, "", iif(eval("misc_text_2") like "NA", "None", iif(eval("misc_text_2") like "KP1", "Kitchen Printer 1", iif(eval("misc_text_2") like "KP2", "Kitchen Printer 2", iif(eval("misc_text_2") like "KP3", "Kitchen Printer 3", iif(eval("misc_text_2") like "BP1", "Bar Printer 1", iif(eval("misc_text_2") like "BP2", "Bar Printer 2", iif(eval("misc_text_2") like "BP3", "Bar Printer 3", Eval("misc_text_2")))))))))%>'></asp:Label>

I keep on getting an error Exception Details: System.InvalidCastException: Conversion from type 'DBNull' to type 'String' is not valid.

I know I'm missing something, but what...

Thanks in advance

Answer

Lasse V. Karlsen picture Lasse V. Karlsen · Feb 11, 2009

You must explicitly check for DBNull.Value and do the conversion yourself.

In other words, build a method that will do the conversion for you, taking DBNull.Value into account.