Hi,
I have a question, I would like to know how can I add pictures to my datagrid? On my DB I have all images path ex.(/images/image001.jpg), is there a way that I can display that picture in the datagrid.
Thank You
Ennio Bozzetti

Dani AI

Generated

Ennio asked how to show image files (paths stored in the DB) inside a DataGrid. Several good directions are already in the thread — pointed to binding during item data events, and others showed examples, and / correctly pushed the Template route — but a few practical, up-to-date notes and quick fixes make this reliably work across scenarios.

Use a TemplateColumn with a server Image control (so you can safely FindControl from code-behind or bind declaratively). Example DataGrid markup (replace the field name with your column):

<asp:DataGrid id="dgPhotos" runat="server" AutoGenerateColumns="False">
  <Columns>
    <asp:TemplateColumn HeaderText="Photo">
      <ItemTemplate>
        <asp:Image ID="imgPhoto" runat="server"
          ImageUrl='<%# ResolveUrl(Eval("ImagePath").ToString()) %>'
          Width="80" />
      </ItemTemplate>
    </asp:TemplateColumn>
    <!-- other columns -->
  </Columns>
</asp:DataGrid>

If you need to set the URL in code-behind (ItemDataBound), prefer FindControl + safe casting and null checks instead of indexing Controls[]. This avoids the common "Specified cast is not valid" when the control you expect isn't at that index:

protected void dgPhotos_ItemDataBound(object sender, DataGridItemEventArgs e)
{
  if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
  {
    var img = e.Item.FindControl("imgPhoto") as System.Web.UI.WebControls.Image;
    if (img != null)
    {
      string path = DataBinder.Eval(e.Item.DataItem, "ImagePath") as string;
      img.ImageUrl = ResolveUrl(path ?? "~/images/missing.png");
    }
  }
}

Quick troubleshooting checklist (addressing issues raised by and others):

  • Ensure the image is a server control (runat="server" and an ID), otherwise it won't appear in FindControl.
  • Avoid casting e.Item.Cells[n].Controls[m] unless you confirm the exact control type and index — enumerate GetType() in debug to inspect the Controls collection first.
  • Never set ImageUrl to a server filesystem path (e.g., D:\...) — use virtual paths (~/images/...) or an image handler (/Image.ashx?id=123) when serving blobs from a DB.
  • For performance, serve thumbnails, enable caching, and use loading="lazy" on modern sites.

If migrating or starting fresh, prefer GridView/ListView (more features and cleaner templates) over the older DataGrid.

Recommended Answers

All 9 Replies

Set the Image.ImageURL property for your image control from the database field in the itemdatabound event of the datagrid :) Sorry it's a little brief much rush :)

Hello

I have the same question about using Images in a datagrid.
I want to bind the image dynamically in ItemBound event.
I am having trouble figuring it out. Below is my code:

if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
System.Web.UI.WebControls.Image imgDaily = CType(e.Item.Cells[2].Controls[1],System.Web.UI.WebControls.Image);



if(e.Item.Cells[2].Equals("1"))
imgDaily.ImageUrl = "./Images/yes.jpg";
else if(e.Item.Cells[2].Equals("1"))
imgDaily.ImageUrl = "./Images/no.jpg";
}

I think the CType is a VB format. I need to write the code in C#,
somebody pls help me.

Thanks
Sandy

Hello

I have the same question about using Images in a datagrid.
I want to bind the image dynamically in ItemBound event.
I am having trouble figuring it out. Below is my code:

if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
System.Web.UI.WebControls.Image imgDaily = CType(e.Item.Cells[2].Controls[1],System.Web.UI.WebControls.Image);



if(e.Item.Cells[2].Equals("1"))
imgDaily.ImageUrl = "./Images/yes.jpg";
else if(e.Item.Cells[2].Equals("1"))
imgDaily.ImageUrl = "./Images/no.jpg";
}

I think the CType is a VB format. I need to write the code in C#,
somebody pls help me.

Thanks
Sandy

Hey.. i got it.. if someone else is looking for the same.. here is the solution from
http://www.dotnetbips.com/29E37690-7C6D-474E-836C-9F72BC53C27A.aspx?articleid=101:

private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
System.Web.UI.WebControls.Image anImagine ;
if(e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item )
{
anImagine = ((System.Web.UI.WebControls.Image)e.Item.Cells[1].Controls[1]); anImagine.ImageUrl="icons/" + e.Item.Cells[0].Text.ToString() + ".gif";
}
}

- Sandy

Hey.. i got it.. if someone else is looking for the same.. here is the solution from
http://www.dotnetbips.com/29E37690-7C6D-474E-836C-9F72BC53C27A.aspx?articleid=101:

private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
System.Web.UI.WebControls.Image anImagine ;
if(e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item )
{
anImagine = ((System.Web.UI.WebControls.Image)e.Item.Cells[1].Controls[1]); anImagine.ImageUrl="icons/" + e.Item.Cells[0].Text.ToString() + ".gif";
}
}

- Sandy

I have do the same but it cause error
"Specified cast is not valid." at the line code.

anImagine = ((System.Web.UI.WebControls.Image)e.Item.Cells[1].Controls[1]);

I want to display images in the datagrid of the asp.net framework 1.1.

private void dgCategory_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
		{
			System.Web.UI.WebControls.Image img;
			if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
			{				
				img = ((System.Web.UI.WebControls.Image)e.Item.Cells[3].Controls[0]);
				img.ImageUrl =@"D:\ACCP2005\Semester III\ASP.Net\Excerices\ASP Examination\Images\baokhac24-04-08_pic1.gif";
			}
		}

but it cause error "Specified cast is not valid"
at the line code img = ((System.Web.UI.WebControls.Image)e.Item.Cells[3].Controls[0]);

try like this for gridview same will work for any databoundcontrol with small changes

<asp:TemplateField >
        <ItemTemplate >
            <asp:Image ID="Image1" runat="server" ImageUrl ='<%# "~/Images/"+Eval("filenamefromdb") %>' />
        </ItemTemplate>
        </asp:TemplateField>

try this one dear!!!!!!!!!!!!

<asp:DataList ID="dlList" runat="server" DataKeyField="ID" 
                onitemdatabound="dlList_ItemDataBound">
                <ItemTemplate>
                    <table border="0" cellpadding="0" cellspacing="0" width="100%">
                                <tr>
                                    <td align="center">
                                        <a href='<%#Eval("Link") %>' target="_blank">
                                            <%-- <img src="WebAdmin/LogoHandler.ashx?ID=<%# Eval("ID") %>" style="border: 0px solid white" />--%>
                                            <asp:Image ID="Image2" runat="server" />    
                                        </a><br />
                                        <br />
                                    </td>
                                </tr>
                            </table>
                </ItemTemplate>
            </asp:DataList>
protected void dlList_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
        {
            Image Image2 = (Image)e.Item.FindControl("Image2");
            DataTable dt = GetSponsors();
            if (dt.Rows.Count > 0)
            {
                string lstrImageName = Convert.ToString(DataBinder.Eval(e.Item.DataItem, "Logo"));
                Image2.ImageUrl = "~/_Images/Thumbnail/" + lstrImageName;
            }
        }
    }

    public DataTable GetSponsors()
    {
        DataTable dt = new DataTable();
        using (SqlCommand Com = new SqlCommand())
        {
            Com.CommandText = "GetSponsors";
            GetDataTable(Com);

            dt = GetDataTable(Com);
           
            return dt;
        }
    }
    public static DataTable GetDataTable(SqlCommand com)
    {
        using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["GITSystemConnection"].ConnectionString))
        {
            using (DataSet ds = new DataSet())
            {
                using (SqlDataAdapter adp = new SqlDataAdapter(com))
                {
                    adp.SelectCommand.Connection = con;
                    adp.SelectCommand.CommandType = CommandType.StoredProcedure;
                    adp.Fill(ds);

                }
                return ds.Tables[0];
            }
        }
    }

//stored procedure

Create PROCEDURE [dbo].[GetSponsors]  

AS  
BEGIN  
  
 Select   ID,Logo,Link  
         From Sponsors   
END

------------------------------
Life's battle don't always go to the stronger or faster man. But sooner or later, the man who wins, is the man who thinks he can.

please mark the thread as its really helpfull

commented: This is an old thread. Do not reply. +0

Template is the only cure to your solution

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.