Link to home
Start Free TrialLog in
Avatar of sam20
sam20

asked on

Display images from a folder in GridView

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

Avatar of Dirk Haest
Dirk Haest
Flag of Belgium image

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" />
Avatar of sam20
sam20

ASKER

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

Can you show your InsertCommand !
Avatar of sam20

ASKER

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;
    }
}
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 ?
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
Avatar of sam20

ASKER

If it is ok so I can send the hole project to you (or tell me exactly which file I should send to you.)
>> 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 !
Avatar of sam20

ASKER

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>
Can you show the properties of ContentListDataSource
Avatar of sam20

ASKER

sorry, where can I find those properties?
How did you tell to your datagrid how to get the data ?
Avatar of sam20

ASKER

Sorry, is it not the code I send you already in the first code snippet?
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" />
Avatar of sam20

ASKER

Got this error:
The data types varchar and varchar are incompatible in the '&' operator.
SelectCommand="SELECT '~/media/' + [imagename] as ImageWithPath, datail, description, price, productname FROM tblImages">
Avatar of sam20

ASKER

DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'id'.
ASKER CERTIFIED SOLUTION
Avatar of Dirk Haest
Dirk Haest
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of sam20

ASKER

That works, thank you very much.