Andy Jr.
Andy Jr.

Reputation: 105

How to hide a broken ASP.NET Image Control

I've only been able to find how to hide broken images for an image added with tag.

i.e.<img src="sample.jpg" onerror="this.style.display='none';">

How would I do this in .net with an image control?

Here's my code:

<asp:Image AlternateText='<%#Eval("DisplayName") %>'  ID="newsImage" width="77" height="57" align="middle" valign="top" runat="server"  Visible='<%# Eval("ImageName").ToString() != "" %>'  ImageUrl='<%#String.Format("../images/products/{0}", Eval("ImageName")) %>' />

Upvotes: 0

Views: 908

Answers (2)

Win
Win

Reputation: 62290

If you just care about not displaying a broken image in client-browser, you can just use -

<asp:Image ... onerror="this.style.display='none';" />

Upvotes: 3

VDWWD
VDWWD

Reputation: 35544

Here are 2 possibilities. You can hide the Image or change the url to a noimage.jpg for example when the file is not found.

<asp:Image Visible='<%# System.IO.File.Exists(Server.MapPath(String.Format("../images/products/{0}", Eval("ImageName")))) %>' ImageUrl='<%# String.Format("../images/products/{0}", Eval("ImageName")) %>' runat="server" ID="Image1" />

<asp:Image ImageUrl='<%# System.IO.File.Exists(Server.MapPath(String.Format("../images/products/{0}", Eval("ImageName")))) ? String.Format("../images/products/{0}", Eval("ImageName")) : "no-image.jpg" %>' runat="server" ID="Image2" />

Upvotes: 1

Related Questions