How to conditionally show an image, or other control in ASP.NET

Quite often, you want to display an item from a database that may or may not have an associated image. Examples might include a news story, product details, car for sale etc. But you want to avoid the dreaded "redex" if a picture isn't present.

If you bind the image to an <asp: Image> control you can toggle the Visibility property from true to false, depending on the existence of an image, or image file path in the returned records. Here are some ways to achieve that.
C#:
Visible='<%# Eval("ImageFile")!=DBNull.Value %>' 
Or
Visible='<%# Eval("ImageFile")==DBNull.Value ? false: true %>'  
Or, if using a DataSource Control, this can be handled in the Item_DataBound Event:

VB.Net
Visible=<%# IIf(Eval("ImageFile") Is DbNull.Value, "False","True") %>'
Or
Visible='<%# Eval("ImageFile")<>DBNull.Value %>'

You might also like...