Solving “Image Not Found” Problem In GridView


With GridView control you have an option to show images by using ImageField column type or TemplateField. By using images your web application could look richer and more professional. But, there is a common problem, what if image file not exists because of some reason? What would happen then? Well, in that case your web application will not be richer and certainly not look professional. If some image in GridView not exists, ugly red X will be shown, for code snippet above it could produce output like this: // We need these namespaces using System.Web.UI.WebControls; using System.IO; … protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { Image CurrentImage = (Image)e.Row.FindControl(“imgLogo”); if (!File.Exists(Server.MapPath(CurrentImage.ImageUrl))) { // if image not exists, use default image CurrentImage.ImageUrl = “~/Images/DefaultImage.gif”; } } } Now, when we run the code, output will be more user friendly. If some image is missing, default image will be displayed in GridView:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s