Having a “No image available” if your image URL errors out – RadGrid

by Yugolancer


Posted on Friday, January 8, 2016



It often happens that you’ve got no image for all the items in your store.

It could be caused by different reasons like your server where you host the images is temporary down, the third party cannot serve the image at the moment or you just have no appropriate image at the moment. Anyway this is how you should keep your store consistent without those broken image icons that internet browsers add in there.

Usually i do that from code-behind like the following:

VB.NET code:


Protected Sub RadGrid1_ItemDataBound(sender As Object, e As GridItemEventArgs) Handles RadGrid1.ItemDataBound
        ' set the markup for each item
        If TypeOf e.Item Is GridDataItem Then
            Dim dataItem As GridDataItem = CType(e.Item, GridDataItem)            
 
            Dim thumbnail As Image = CType(dataItem.FindControl("imageThumbnail"), Image)
            If thumbnail IsNot Nothing Then
                Dim imagedbvalue As String = DataBinder.Eval(dataItem.DataItem, "imageThumbnail").ToString
                thumbnail.ImageUrl = imagedbvalue
                ' if the image does not exist we load an image with "photo coming soon" title
                Dim comingsoon As String = "http://" & Request.Url.Host & "/images/ComingSoon.jpg"
                thumbnail.Attributes.Add("onerror", "this.src= '" & comingsoon & "';")
            End If
            ' other code 
       End If
End Sub

C# code:


protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
{
	// set the markup for each item
	if (e.Item is GridDataItem) {
	        GridDataItem dataItem = (GridDataItem)e.Item;
 
		Image thumbnail = (Image)dataItem.FindControl("imageThumbnail");
		if (thumbnail != null) {
			string imagedbvalue = DataBinder.Eval(dataItem.DataItem, "imageThumbnail").ToString;
			thumbnail.ImageUrl = imagedbvalue;
			// if the image does not exist we load an image with "photo coming soon" title
			string comingsoon = "http://" + Request.Url.Host + "/images/ComingSoon.jpg";
			thumbnail.Attributes.Add("onerror", "this.src= '" + comingsoon + "';");
		}
		// other code 
	}
}


Copyright © ASPNETer 2006 - 2016