Display no image in GridView ImageField when image does not exist in ASP.Net

Last Reply 2 months ago By pandeyism

Posted 2 months ago

How to accept null (image)values in gridview

how to set default image to the image field which are null values

You are viewing reply posted by: pandeyism 2 months ago.
Posted 2 months ago Modified on 2 months ago

Hi Faizal,

Please take reference to the below code and correct your code.

If you want to  show No Image in place of null values, so you can do like that, refer below smaple.

HTML

<div>
    <asp:GridView ID="gvImages" runat="server" AutoGenerateColumns="false" OnRowDataBound="OnRowDataBound">
        <Columns>
            <asp:BoundField DataField="Id" HeaderText="Id" />
            <asp:BoundField DataField="Name" HeaderText="Name" />
            <asp:TemplateField HeaderText="Image">
                <ItemTemplate>
                    <asp:Image ID="Image1" runat="server" Height="50px" Width="50px" ImageUrl='<%# Eval("ImagePath") %>' />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
</div>

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        System.Data.DataTable dt = new System.Data.DataTable();
        dt.Columns.AddRange(new System.Data.DataColumn[] { 
            new System.Data.DataColumn("Id", typeof(int)), 
            new System.Data.DataColumn("Name", typeof(string)), 
            new System.Data.DataColumn("ImagePath", typeof(string)) });
        dt.Rows.Add(1, "Koala.jpg", "~/images/Koala.jpg");
        dt.Rows.Add(2, "Lighthouse.jpg", "~/images/Lighthouse.jpg");
        dt.Rows.Add(3, "Desert.jpg", "~/images/Desert.jpg");
        dt.Rows.Add(4, "Hydrangeas.jpg", "");
        this.gvImages.DataSource = dt;
        this.gvImages.DataBind();
    }
}

protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        string imageName = e.Row.Cells[1].Text;
        if (!System.IO.File.Exists(Server.MapPath("~/images/") + imageName))
        {
            (e.Row.FindControl("Image1") as Image).ImageUrl = "~/images/NoImage.png";
        }
    }
}

Screenshot

If you are using ImageField then you can assign NullImageUrl to display default image.

<asp:ImageField DataImageUrlField="ImagePath" HeaderText="Image" NullImageUrl="~/images/NoImage.png">
</asp:ImageField>