Bind image from SQL Server database (image field) to Ad Rotator

693 Views Asked by At

I have searched stackoverflow for answers but couldn't find anything that would help me.

I am trying to get an Ad Rotator that will display images stored in the database. There will be 5 different ads for different products. The products are stored in a cookie and will be different after each order. I know that I have to retrieve the binary from the db and convert it to image. This is what I have tried (just testing for one product for now. I can then use a foreach loop or something, want to get the right idea first):

using (System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(strconn))
    {
        SqlCommand cmdSelect = new SqlCommand("select Image from Products where ProductID = '1'", con); 
        con.Open();
        byte[] barrImg = (byte[])cmdSelect.ExecuteScalar();
        string strfn = Convert.ToString(DateTime.Now.ToFileTime());
        FileStream fs = new FileStream(strfn,
        FileMode.CreateNew, FileAccess.Write);
        fs.Write(barrImg, 0, barrImg.Length);
        fs.Flush();
        fs.Close();
        Image IMG = Image.FromFile(strfn);
    }

But this code doesn't work. I get an error message saying

Error   1   'System.Web.UI.WebControls.Image' does not contain a definition for 'FromFile'  

So my I have 2 questions: 1. What is the proper way of doing this? 2. How do I assign the correct values to the ImageUrl field in the XML file for Ad Rotator?

Thank you in advance for any help!

1

There are 1 best solutions below

0
renanroncarati On

you can try this way, using less lines of code, using MemoryStream instead of File:

using (System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(strconn))
 {
        SqlCommand cmdSelect = new SqlCommand("select Image from Products where ProductID = '1'", con); 
        con.Open();
        byte[] barrImg = (byte[])cmdSelect.ExecuteScalar();
        MemoryStream ms = new MemoryStream(barrImg);
        Image IMG = Image.FromStream(strfn);
  }