Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Image not showing up in my GridView

Posted on 2009-02-23
10
Medium Priority
?
355 Views
Last Modified: 2013-11-26
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

0
Comment
Question by:niceoneishere
  • 4
  • 4
  • 2
10 Comments
 
LVL 11

Assisted Solution

by:jmwheeler
jmwheeler earned 1800 total points
ID: 23715033
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
 
LVL 2

Author Comment

by:niceoneishere
ID: 23715120
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
 
LVL 11

Expert Comment

by:jmwheeler
ID: 23715210
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
NFR key for Veeam Agent for Linux

Veeam is happy to provide a free NFR license for one year.  It allows for the non‑production use and valid for five workstations and two servers. Veeam Agent for Linux is a simple backup tool for your Linux installations, both on‑premises and in the public cloud.

 
LVL 27

Expert Comment

by:nmarun
ID: 23715241
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
 
LVL 11

Accepted Solution

by:
jmwheeler earned 1800 total points
ID: 23715349
<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
 
LVL 2

Author Comment

by:niceoneishere
ID: 23721142
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
 
LVL 11

Expert Comment

by:jmwheeler
ID: 23721163
You need to specify a href for the anchor.

ex:

<a href="nextpage.aspx"><img ...... /></a>
0
 
LVL 2

Author Comment

by:niceoneishere
ID: 23722621
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
 
LVL 27

Assisted Solution

by:nmarun
nmarun earned 200 total points
ID: 23722924
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
 
LVL 2

Author Closing Comment

by:niceoneishere
ID: 31550271
Thanks a lot you guys Rock
0

Featured Post

Free learning courses: Active Directory Deep Dive

Get a firm grasp on your IT environment when you learn Active Directory best practices with Veeam! Watch all, or choose any amount, of this three-part webinar series to improve your skills. From the basics to virtualization and backup, we got you covered.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
Are you ready to place your question in front of subject-matter experts for more timely responses? With the release of Priority Question, Premium Members, Team Accounts and Qualified Experts can now identify the emergent level of their issue, signal…
Whether it be Exchange Server Crash Issues, Dirty Shutdown Errors or Failed to mount error, Stellar Phoenix Mailbox Exchange Recovery has always got your back. With the help of its easy to understand user interface and 3 simple steps recovery proced…
Suggested Courses

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question