Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2534
  • Last Modified:

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

0
sam20
Asked:
sam20
  • 10
  • 9
1 Solution
 
DhaestCommented:
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
 
sam20Author Commented:
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
 
DhaestCommented:
Can you show your InsertCommand !
0
What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

 
sam20Author Commented:
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
 
DhaestCommented:
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
 
DhaestCommented:
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
 
sam20Author Commented:
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
 
DhaestCommented:
>> 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
 
sam20Author Commented:
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
 
DhaestCommented:
Can you show the properties of ContentListDataSource
0
 
sam20Author Commented:
sorry, where can I find those properties?
0
 
DhaestCommented:
How did you tell to your datagrid how to get the data ?
0
 
sam20Author Commented:
Sorry, is it not the code I send you already in the first code snippet?
0
 
DhaestCommented:
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
 
sam20Author Commented:
Got this error:
The data types varchar and varchar are incompatible in the '&' operator.
0
 
DhaestCommented:
SelectCommand="SELECT '~/media/' + [imagename] as ImageWithPath, datail, description, price, productname FROM tblImages">
0
 
sam20Author Commented:
DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'id'.
0
 
DhaestCommented:
SelectCommand="SELECT id, '~/media/' + [imagename] as ImageWithPath, datail, description, price, productname FROM tblImages">
0
 
sam20Author Commented:
That works, thank you very much.
0

Featured Post

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

  • 10
  • 9
Tackle projects and never again get stuck behind a technical roadblock.
Join Now