-1

Failing to display an image in gridview. No error messages, just displays the image icon instead of actual image from database

I have a gridview, and I am using RowDataBound event to displays information in labels. I have an Image control in the gridview

<asp:TemplateField HeaderText="Picture">
                    <ItemTemplate>
                        <asp:Image ID="imgPicture" runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>

The image path is stored in database under a column called Image like Images\image.jpg It's stored in a folder called Images in the solution

RowDataBound

        Image imgPicture = (Image)e.Row.FindControl("imgPicture");
        if ((imgPicture != null))
        {
            imgPicture.ImageUrl = @"~\Images\" + (string)DataBinder.Eval(e.Row.DataItem, "Image");
        }
ewjfhweufh
  • 17
  • 1
  • 6
  • Check it our [here](http://www.aspsnippets.com/Articles/Display-images-from-SQL-Server-Database-in-ASP.Net-GridView-control.aspx). Clearly explained on how to display images in gridview – Nad Apr 28 '15 at 12:48
  • @nadeem Thank you for the link, I've displayed images before with Eval but tried out the RowDataBound, I think Eval is better – ewjfhweufh Apr 28 '15 at 13:08
  • Yes, you can try that with`Eval` rather than using `RowDataBound` – Nad Apr 28 '15 at 13:09

1 Answers1

1

i would not use the RowDataBound-Event:

 <asp:TemplateField HeaderText="Picture">
    <ItemTemplate>
        <asp:Image ID="imgPicture" runat="server" ImageUrl='<%# Eval("Image", "~/Images/{0}") %>' />
    </ItemTemplate>
</asp:TemplateField>
fubo
  • 44,811
  • 17
  • 103
  • 137
  • Would it still work if I am using rowdatabound event for other controls? – ewjfhweufh Apr 28 '15 at 12:57
  • yes but you don't have to care about the image control inside the event – fubo Apr 28 '15 at 12:59
  • Thanks, it works now. I've displayed images before with Eval but tried out the RowDataBound, I think Eval is better but not sure why. Could you explain to me why it is better this way please – ewjfhweufh Apr 28 '15 at 13:10
  • 1
    @ewjfhweufh - less code, easier to read/maintain, less to care about (`if ((imgPicture != null))`) – fubo Apr 28 '15 at 13:20