Solved

Display images from a folder  in GridView

Posted on 2008-10-29
19
2,493 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
ID: 22838757
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
ID: 22839154
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
ID: 22839162
Can you show your InsertCommand !
0
Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

 

Author Comment

by:sam20
ID: 22839196
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
ID: 22839207
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
ID: 22839208
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
ID: 22839239
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
ID: 22839249
>> 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
ID: 22839281
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
 
LVL 53

Expert Comment

by:Dhaest
ID: 22839286
Can you show the properties of ContentListDataSource
0
 

Author Comment

by:sam20
ID: 22839334
sorry, where can I find those properties?
0
 
LVL 53

Expert Comment

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

Author Comment

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

Expert Comment

by:Dhaest
ID: 22839409
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
ID: 22839453
Got this error:
The data types varchar and varchar are incompatible in the '&' operator.
0
 
LVL 53

Expert Comment

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

Author Comment

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

Accepted Solution

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

Author Comment

by:sam20
ID: 22839527
That works, thank you very much.
0

Featured Post

Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

Question has a verified solution.

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

Recently while returning home from work my wife (another .NET developer) was murmuring something. On further poking she said that she has been assigned a task where she has to serialize and deserialize objects and she is afraid of serialization. Wha…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
Finding and deleting duplicate (picture) files can be a time consuming task. My wife and I, our three kids and their families all share one dilemma: Managing our pictures. Between desktops, laptops, phones, tablets, and cameras; over the last decade…

730 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