Solved

Display images from a folder  in GridView

Posted on 2008-10-29
19
2,481 Views
Last Modified: 2013-11-26
Hi Experts!
I need some help please. I am trying to display images from a folder called media in GridView. (See please code in code snippet) The gridview (below) contains also ImageFields and it works fine and shows images if you place images in the root of project under solution explorer.
I wonder how I can make it to display images from the folder media instead.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" DataKeyNames="id" DataSourceID="ContentListDataSource" ForeColor="#333333" GridLines="None" Width="732px">

<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />

<Columns>

<asp:BoundField DataField="id" HeaderText="ID" ReadOnly="True" SortExpression="id" />
 

<asp:ImageField DataImageUrlField="imagename" HeaderText="Foto" /> 
 

<asp:BoundField DataField="datail" HeaderText="Datalj" SortExpression="datail" />

<asp:BoundField DataField="description" HeaderText="Beskrivning" SortExpression="description" />

<asp:BoundField DataField="price" HeaderText="Pris" SortExpression="price" />

<asp:BoundField DataField="productname" HeaderText="Produktnamn" SortExpression="productname" />

<asp:CommandField ButtonType="Image" DeleteImageUrl="~/media/delete.gif" ShowDeleteButton="True">

<ItemStyle Width="1px" />

</asp:CommandField>/> 

</Columns>

Open in new window

0
Comment
Question by:sam20
  • 10
  • 9
19 Comments
 
LVL 53

Expert Comment

by:Dhaest
Comment Utility
How do you load the data from your database ? Perhaps you can perform something like this:
select description, price, "~media/" & imagename as ImageWithPath from ...

<asp:ImageField DataImageUrlField="ImageWithPath" HeaderText="Foto" />
0
 

Author Comment

by:sam20
Comment Utility
Hi Dhaest
Thanks for reply
DataImageUrlField="ImageWithPath" gave me error as:
A field or property with the name 'media/imagename' was not found on the selected data source.
I could not make load data to works as you told me. Can you please take a look the load data in code snippet.

<asp:SqlDataSource ID="ContentDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"

DeleteCommand="DELETE FROM tblImages WHERE [imagename]=@imagename" InsertCommand="INSERT INTO tblImages([imagename],img,datail,description,price,productname) VALUES(@imagename,@img,@datail,@description,@price,@productname)"

OnDeleting="ContentDataSource_Deleting" OnInserting="ContentDataSource_Inserting" SelectCommand="SELECT [imagename], datail, description, price, productname FROM tblImages">

<DeleteParameters>

<asp:Parameter Name="imagename" />

</DeleteParameters>

<InsertParameters>

                <asp:Parameter Name="imagename" />

                <asp:Parameter Name="img" />

                <asp:Parameter Name="datail" />

                <asp:Parameter Name="description" />

                <asp:Parameter Name="price" />

                <asp:Parameter Name="productname" />

</InsertParameters>

</asp:SqlDataSource>

<asp:SqlDataSource ID="ContentListDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"

DeleteCommand="DELETE FROM tblImages WHERE id=@id" SelectCommand="SELECT id, [imagename], datail, description, price, productname FROM tblImages">

<DeleteParameters>

<asp:Parameter Name="id" />

</DeleteParameters>

</asp:SqlDataSource>

Open in new window

0
 
LVL 53

Expert Comment

by:Dhaest
Comment Utility
Can you show your InsertCommand !
0
 

Author Comment

by:sam20
Comment Utility
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Linq;
using System.Xml.Linq;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
    protected void Button1_Click(object sender, EventArgs e)
    {
        string strFileName;
        strFileName = FileUpload1.PostedFile.FileName;
        string c = System.IO.Path.GetFileName(strFileName);
        try
        {
            if (!System.IO.Directory.Exists(Server.MapPath("/media/")))
            {
                System.IO.Directory.CreateDirectory(Server.MapPath("/media/"));
            }
            FileUpload1.PostedFile.SaveAs(Server.MapPath("/media/") + FileUpload1.FileName);
        }
        catch (Exception exp)
        {
            Span1.InnerHtml = "Välj en bild";
        }
        if (FileUpload1.HasFile)
        {
            // delete and content with the same name
            ContentDataSource.Delete();
            // insert new content
            ContentDataSource.Insert();
            // refresh the content list
            GridView1.DataBind();
        }
    }
    protected void ContentDataSource_Inserting(object sender, SqlDataSourceCommandEventArgs e)
    {
        e.Command.Parameters["@imagename"].Value = FileUpload1.FileName;
        e.Command.Parameters["@datail"].Value = TextBox4.Text;
        e.Command.Parameters["@description"].Value = TextBox3.Text;
        e.Command.Parameters["@price"].Value = TextBox2.Text;
        e.Command.Parameters["@productname"].Value = TextBox1.Text;
        e.Command.Parameters["@img"].Value = FileUpload1.FileBytes;
    }
    protected void ContentDataSource_Deleting(object sender, SqlDataSourceCommandEventArgs e)
    {
        e.Command.Parameters["@imagename"].Value = FileUpload1.FileName;
    }
}
0
 
LVL 53

Expert Comment

by:Dhaest
Comment Utility
As far as I see, this is just the code to get a file from a harddisk to save it to your server (and a record into your database).
Where is the code to display it in a gridview or load the data into your gridview ?
On which statement exactly do you get an error ?
0
 
LVL 53

Expert Comment

by:Dhaest
Comment Utility
private void gridview_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";
}
}

GridView Examples for ASP.NET 2.0: Displaying Images in a GridView Column
http://msdn.microsoft.com/en-us/library/aa479350.aspx

Loading Images Asynchronously Inside an ASP.NET GridView
http://www.dotnetcurry.com/ShowArticle.aspx?ID=193&AspxAutoDetectCookieSupport=1
0
 

Author Comment

by:sam20
Comment Utility
If it is ok so I can send the hole project to you (or tell me exactly which file I should send to you.)
0
 
LVL 53

Expert Comment

by:Dhaest
Comment Utility
>> the whole project
Therefore I have no intrest ... I just want to know how you retrieve your data back from your database into your grid and where exactly you get the error !
0
 

Author Comment

by:sam20
Comment Utility
It just shows images if you place images in the root of project under solution explorer.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
DataKeyNames="id" DataSourceID="ContentListDataSource" ForeColor="#333333"
GridLines="None" Width="732px">
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<Columns>
<asp:BoundField DataField="id" HeaderText="ID" ReadOnly="True" SortExpression="id" />
<asp:ImageField DataImageUrlField="imagename" HeaderText="Foto" />
<asp:BoundField DataField="datail" HeaderText="Datalj" SortExpression="datail" />
<asp:BoundField DataField="description" HeaderText="Beskrivning" SortExpression="description" />
<asp:BoundField DataField="price" HeaderText="Pris" SortExpression="price" />
<asp:BoundField DataField="productname" HeaderText="Produktnamn" SortExpression="productname" />
<asp:CommandField ButtonType="Image" DeleteImageUrl="~/media/delete.gif" ShowDeleteButton="True">
<ItemStyle Width="1px" />
</asp:CommandField>
0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 53

Expert Comment

by:Dhaest
Comment Utility
Can you show the properties of ContentListDataSource
0
 

Author Comment

by:sam20
Comment Utility
sorry, where can I find those properties?
0
 
LVL 53

Expert Comment

by:Dhaest
Comment Utility
How did you tell to your datagrid how to get the data ?
0
 

Author Comment

by:sam20
Comment Utility
Sorry, is it not the code I send you already in the first code snippet?
0
 
LVL 53

Expert Comment

by:Dhaest
Comment Utility
I overlooked the SelectCommand.
Change this:
SelectCommand="SELECT id, [imagename], datail, description, price, productname FROM tblImages"
into
SelectCommand="SELECT ' ' & [imagename] as ImageWithPath, datail, description, price, productname FROM tblImages">

And change this
<asp:ImageField DataImageUrlField="imagename" HeaderText="Foto" />
into
<asp:ImageField DataImageUrlField="ImageWithPath" HeaderText="Foto" />
0
 

Author Comment

by:sam20
Comment Utility
Got this error:
The data types varchar and varchar are incompatible in the '&' operator.
0
 
LVL 53

Expert Comment

by:Dhaest
Comment Utility
SelectCommand="SELECT '~/media/' + [imagename] as ImageWithPath, datail, description, price, productname FROM tblImages">
0
 

Author Comment

by:sam20
Comment Utility
DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'id'.
0
 
LVL 53

Accepted Solution

by:
Dhaest earned 500 total points
Comment Utility
SelectCommand="SELECT id, '~/media/' + [imagename] as ImageWithPath, datail, description, price, productname FROM tblImages">
0
 

Author Comment

by:sam20
Comment Utility
That works, thank you very much.
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Suggested Solutions

IP addresses can be stored in a database in any of several ways.  These ways may vary based on the volume of the data.  I was dealing with quite a large amount of data for user authentication purpose, and needed a way to minimize the storage.   …
Summary Displaying images in RichTextBox is a common requirement with limited solutions available. Pasting through clipboard or embedding into RTF content only support static images.  This article describes how to insert Windows control objects int…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…

763 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

Need Help in Real-Time?

Connect with top rated Experts

6 Experts available now in Live!

Get 1:1 Help Now