Display Default Image when No Image Found

Here’s a solution to display a Default Image in the Image control, when the original image is not available. The same solution can be applied to both ASP.NET Image Controls as well as HTML image controls

ASP.NET Image Control

<asp:Image ID="imgProd" runat="server"
onerror="this.onload = null; this.src='ImageurlORAnyImageHere.jpg';"/>

HTML Image Control

<img id="imgProd1" src="someimage.gif"
onerror="this.onerror=null; this.src='ImageurlORAnyImageHere.jpg';" />

We are using the onerror event of the image tag, which triggers if there is an error while loading an image. If an error occurs, we display 'ImageurlORAnyImageHere.jpg' as the default image. You can even add an image url.

If you are looking out to apply the same technique while loading images in an ASP.NET GridView, check my article Loading Images Asynchronously Inside an ASP.NET GridView






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

6 comments:

Anonymous said...

Work perfectly!!

carceb said...

Searching for this solution all across the internet and nobody knew how to do it and you in, ONE SIMPLE LINE, solve al my problems THANK ONE MILLION

Suprotim Agarwal said...

Glad to hear it helped you out :)

Unknown said...

Sir, What is the purpose of "this.onerror=null;"?

Suprotim Agarwal said...

onerror is an image event. Here we are setting it to null so that the browsers don't repeatedly fire the error event.

Unknown said...

Thank you, for explanation Sir.