Domanda

I have a datalist with an image control whose aspx code is

    <asp:DataList ID="DataList1" runat="server" 
        RepeatDirection="Horizontal" RepeatColumns="4">
            <ItemTemplate>
                <div>
                    <asp:Image ID="Image1" ImageUrl='<%#Eval("IMAGE") %>' 
                     runat="server" Height="75px" Width="75px" />
                </div>
            </ItemTemplate>
        </asp:DataList>

The code that I'm trying to get images from the database is

    PagedDataSource objds = new PagedDataSource();
        string query = "SELECT * FROM Icon";
        SqlConnection con = new SqlConnection();
        con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ICONBANKConnectionString"].ConnectionString;
        try
        {
            SqlCommand cmd = new SqlCommand(query, con);
            con.Open();
            //SqlDataReader dr = cmd.ExecuteReader();
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = new SqlCommand(query, con);
            DataSet ds = new DataSet();
            da.Fill(ds, "images");
            objds.DataSource = ds.Tables[0].DefaultView;

            DataList1.DataSource = objds;
            DataList1.DataBind();
            con.Close();
        }
        catch (Exception)
        {

            throw;
        }

the sql table looks like this

    Icon( ID, SUBCAT_ID, ALBUM_ID, SUBCAT_NAME, ALBUM_NAME, IMAGE, ICON_SIZE, 
    BLACKWHITE, NAME, DESIGNER, HITS, RATINGS, PRICE)

When I debug the code it shows the table rows in dataset but when I run the page it is not showing me the image.... Kindly guide me what is the problem behind it. One More thing the image was stored in database is in binary format

È stato utile?

Soluzione

You are setting the byte[] or binary data to the ImageURL field, which is wrong. The Image URL expects a path.

Check out this question and the answers :

Convert from binary data to an image control in ASP.NET

On the itemdatabound event of the datalist, find your image control. if you're using the html tag set the src property, if you are using , check out the this answer :

//Find your image control (Image1 lets say) on the item databound event of the datalist.
Byte[] myImage = GetMyImageFromMyDataSource();
String st = Server.MapPath("myImageNameOrID.jpg"); // Try Name + ID to make it unique
FileStream fs = new FileStream(st, FileMode.Create, FileAccess.Write);
fs.Write(myImage, 0, myImage.Length);
fs.Close();
Image1.ImageUrl = "myImageNameOrID.jpg"; 

EDIT : Check out this link to know more about using the itemdatabound event of the datalist :

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.datalist.itemdatabound%28v=vs.110%29.aspx

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top