Search code examples
c#asp.netdatalistsystem.drawing

How to set System.Drawing.Image to System.ui.WebControls.Image in datalist template item


I am making a Bookstore website. I use Visual Studio 2010 and MS SQL Database. I have images about books. I have a Book table in database and there is an image column in this table.

I saved these images (in byte array format) in database.

I tested it in Windows Form Application and everything is ok. I mean i can retrieve and save images to/from database. when I retrieve them from database, i save them (in System.Drawing.Image format) in Book class.

    public Book
    {
          private int id;
          private System.Drawing.Image image;
          // name and other .. informations,  constructor, get and set methods;
    }

    public BookLayer
    {
           // after call this method i can get all informations from database
           public static List<Book> getBooks()
           {
            }
    }

I use datalist with objectdatasource in Asp.net 4 Web Project. I wrote Book and BookLayer class for objectdatasource. I can show all informations in datalist except image. because image is System.Drawing.Image in Book class but image is System.ui.WebControls.Image which in datalist template item. Format is different. How can i do that ? is that way wrong ? Pls give me any advice.


Solution

  • Yes use handler. You can do as Add a template field

     <ItemTemplate>
    <img border="2" width="150px" src="../images/loading.gif" onload="getpic(this,'<%# Eval("bkid")%>');"/>
    </ItemTemplate>
    

    use the following java script function getpic(img, pid) {

    try {
    img.onload = null;
    img.src = '../Getimage.ashx?id=' + pid;
    } catch (e) {
    alert(e);
    }
    }
    </script>
    

    in your getimage.ashx

    byte[] imageBytes = ;// ToDOget your byte
                Bitmap newBmp = ConvertToBitmap(imageBytes);
                if (newBmp != null)
                {
                    newBmp.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                    newBmp.Dispose();
                }