Image not showing up in my GridView

Hello Experts,

i have gridview and 2 of the columns are Itemnumber and Preview. now the Preview displays a thumnail image for the itemnumber. i have used the below code but its not working, can someone tell me where i am making the mistake. I really appreciate it.

all i want is for every itemnumber to show a preview image. all the images are stored in the folder called thumbs and its path is (~/images/products/thumbs)

here is the code below in the code snippet section
 Thanks once again

 
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GVsearch.aspx.cs" Inherits="MySite.GVsearch" %>
<%@ Register TagPrefix="ws" TagName="menu" src="menu.ascx" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>SQL and GV seach page</title>
</head>
<body>
    <form id="form1" runat="server" defaultbutton="btnSearch">
    <div>
    <asp:TextBox id="txtSearch" runat="server" />
 
<asp:Button id="btnSearch" runat="server"
    Text    ="Search"
    OnClick ="btnSearch_OnClick" />
    <br />
<asp:Panel ID="SearchPanel" runat="server" Visible="false">
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:MySite%>"
            SelectCommand="SELECT DISTINCT [ItemNumber], [Title], [Price],[Description] FROM [mysearchtb] WHERE (([Title] LIKE '%' + replace(@Title, ' ', '%') + '%') OR ([ShortDescription] LIKE '%' + replace(@ShortDescription, ' ', '%') + '%') OR ([ShortTitle] LIKE '%' + replace(@ShortTitle, ' ', '%') + '%') OR ([Description] LIKE '%' + replace(@Description, ' ', '%') + '%') OR ([ItemNumber] LIKE '%' + replace(@ItemNumber, ' ', '%') + '%'))" OnSelecting="SqlDataSource1_Selecting" >
            <SelectParameters>
                <asp:Parameter  Name="Title"  Type="String" />
                <asp:Parameter  Name="ShortDescription" Type="String" />
                <asp:Parameter  Name="ShortTitle" Type="String" />
                <asp:Parameter  Name="Description" Type="String" />
                <asp:Parameter  Name="ItemNumber"  Type="String" />
            </SelectParameters>
        </asp:SqlDataSource>
    
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AllowPaging="True" CellPadding="4"
            DataSourceID="SqlDataSource1"   
              OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
            ForeColor="#333333" GridLines="None">
            <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
            <Columns>
                <asp:TemplateField HeaderText="Item Number" ShowHeader="False" SortExpression="ItemNumber">
                    <ItemTemplate>
                        <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="false" 
                            Text='<%# Eval("ItemNumber") %>' CommandName="Select"></asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Item Number" SortExpression="ItemNumber" Visible="False">
                    <ItemTemplate>
                        <asp:Label ID="lbItemNo" runat="server" Text='<%# Bind("ItemNumber") %>' ></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
                <asp:BoundField DataField="Price" HeaderText="Price" SortExpression="Price" DataFormatString="{0:c}" HtmlEncode="False" />
                <asp:TemplateField HeaderText="Available Sizes">
                <ItemTemplate>
                <asp:Label ID="lbitem" runat="server" Visible="false" Text='<%# Bind("ItemNumber") %>' />
                 <asp:DropDownList ID="DropDownList2" runat="server"
                  DataSourceID="SqlDataSource2" DataTextField="Name"
                   DataValueField="ItemNumber" SelectedValue='<%# Bind("ItemNumber") %>' Width="75px">
                    </asp:DropDownList>
                    <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:MySite %>" 
                    SelectCommand="SELECT [ItemNumber], [Name] FROM [mysearchtb] WHERE ([ItemNumber] = @ItemNumber)">
                        <SelectParameters>
                            <asp:ControlParameter ControlID="lbitem" Name="ItemNumber" PropertyName="Text" Type="String" />
                        </SelectParameters>
                    </asp:SqlDataSource>  
                </ItemTemplate>
                </asp:TemplateField>
                 <asp:TemplateField HeaderText="Preview">
                <ItemTemplate>
                <img id="img2" runat="server" src='<%# Eval("ItemNumber", "~/images/products/thumbs/{0}") %>' alt='<%# Eval("Title") %>' />
                </ItemTemplate>
                </asp:TemplateField>
                 
                                
            </Columns>
            <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
            <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
            <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
            <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
            <AlternatingRowStyle BackColor="White" />
        </asp:GridView>
    
 </asp:Panel>   
        
     <br />
      <asp:Label ID="lbnotfound" runat="server"></asp:Label>
      <br />
        <asp:Label ID="lbtest" runat="server"> </asp:Label>
    </div>
   
    </form>
</body>
</html>

Open in new window

LVL 2
niceoneishereAsked:
Who is Participating?
 
jmwheelerConnect With a Mentor Commented:
<img id="img2" runat="server" src='<%# GetImagePath(Eval("ItemNumber"))' % />

[Code-Behind]

public string GetImagePath(object ItemNumber)
{
     string path = Server.MapPath("images/products/thumbs/");
     if (System.IO.File.Exists(String.Format("{0}{1}.jpg", path, ItemNumber.ToString()))
         return String.Format("{0}{1}.jpg", path, ItemNumber.ToString());
     else  if (System.IO.File.Exists(String.Format("{0}{1}.gif", path, ItemNumber.ToString()))
         return String.Format("{0}{1}.gif", path, ItemNumber.ToString());
     else
         return "";
}
0
 
jmwheelerConnect With a Mentor Commented:
Try below.  I think the problem is you are missing the extension for the image.  Substitute your image extension for ".png" in the code below.
<img id="img2" runat="server" src='<%# Eval("ItemNumber", "~/images/products/thumbs/{0}.png") %>' alt='<%# Eval("Title") %>' />

Open in new window

0
 
niceoneishereAuthor Commented:
Hello Sir,
Bravo! but i used .jpg instead of .png and it works now my question is what if  i have images ending with .gif. i dont think it will show those right. is there anyway to show them also
Thanks once again, you rock sir.
 
0
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
jmwheelerCommented:
Do you mean that some of your images are .jpg and some are .gif?  If that is the case then there will be a little more work to do.
0
 
nmarunCommented:
You need to store the image names in the database. One way is to add another column to the 'mysearchtb' table called 'ImageName' or something like that. In this you'll store the actual image name (with extension). This way, you can include the ImageName as a column in your select statement and you'll bind the ImageName field to the img2 image control.

The other way is to standardize all the images to be .png and then you can use jmwheeler's solution.

<img id="img2" runat="server" src='<%# Eval("ImageName", "~/images/products/thumbs/{0}") %>' alt='<%# Eval("Title") %>' />

Open in new window

0
 
niceoneishereAuthor Commented:
ok sir,
thanks for the code snippet. i have one question before i close this post, i have included a anchor tag to make the image clickable but for some reason i dont see the hand icon on the image so it can be clicked.
this is what i have tried
Thanks once again.

<asp:TemplateField HeaderText="Preview">
                <ItemTemplate>
                <a><img id="img1" src='<%# Eval("ItemNumber","~/images/products/thumbs/{0}.jpg") %>' alt='<%# Eval("Title") %>' /></a>
                </ItemTemplate>
                </asp:TemplateField>

Open in new window

0
 
jmwheelerCommented:
You need to specify a href for the anchor.

ex:

<a href="nextpage.aspx"><img ...... /></a>
0
 
niceoneishereAuthor Commented:
Ok Sir,
i have done like this below instead of <a> tag i used a imagebutton and i am making it clickable like below ( NOTE the imagebutton is inside a GridView). its throwing error. i am posting the error also
ERROR
System.NullReferenceException was unhandled by user code
  Message="Object reference not set to an instance of an object."
  Source="App_Web__omge2nv"
  StackTrace:
       at WoodenSoldier.searchbyword.Imgbtn1_Click(Object sender, ImageClickEventArgs e) in c:\Documents and Settings\Tammu\My Documents\Visual Studio 2005\WebSites\testsite\searchbyword.aspx.cs:line 121
       at System.Web.UI.WebControls.ImageButton.OnClick(ImageClickEventArgs e)
       at System.Web.UI.WebControls.ImageButton.RaisePostBackEvent(String eventArgument)
       at System.Web.UI.WebControls.ImageButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
       at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
       at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
       at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
LINE 121 is
ImageButton ib1 = (ImageButton)GridView1.SelectedRow.FindControl("Imgbtn1");
please see the attached code
 Thanks Once again

<asp:TemplateField HeaderText="Preview">
                <ItemTemplate>
                 <asp:ImageButton ID="Imgbtn1" runat="server" ImageUrl='<%# Eval("ItemNumber","~/images/products/thumbs/{0}.jpg") %>'
                     AlternateText='<%# Eval("ItemNumber") %>' ToolTip='<%# Eval("Title") %>' OnClick="Imgbtn1_Click"    />
                 </ItemTemplate>
                 </asp:TemplateField>
 
CODE BEHIND
 
protected void Imgbtn1_Click(object sender, ImageClickEventArgs e)
        {
           
            ImageButton ib1 = (ImageButton)GridView1.SelectedRow.FindControl("Imgbtn1");
            if (ib1 != null)
            {
                string itnum = ib1.AlternateText.Trim().ToUpper();
                BrowsableBookItem result = this.CurrentBook.GetItem(itnum);
                if (result == null)
                {
                    lbnotfound.Visible = true;
                    lbnotfound.Text = "Item Not Found";
                }
                else if (result is Product)
                {
                    Server.Transfer(string.Format("browse/bookitems.aspx?bid={0}&pid={1}",
                        this.CurrentBook.Id,
                        result.Id));
                }
                else
                {
                    Server.Transfer(string.Format("browse/ensembleitems.aspx?bid={0}&eid={1}",
                        this.CurrentBook.Id,
                        result.Id));
                }
            }
        }

Open in new window

0
 
nmarunConnect With a Mentor Commented:
See if you can do this:

//instead of 
ImageButton ib1 = (ImageButton)GridView1.SelectedRow.FindControl("Imgbtn1");
// try this
ImageButton ib1 = (ImageButton)sender;

Open in new window

0
 
niceoneishereAuthor Commented:
Thanks a lot you guys Rock
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.