May 28, 2013

Display Images From Database in DataList Control

In this post, I'm showing you how to bind images directly from database using Asp.net control DataList. Directly from database means images are not store on physical place and need to retrieve it from database, where it present as binary format. 

First we convert image from binary format into byte format then using Asp.Net Handle (.ashx) bind image to DataList Image controller.

------------------
ASPX Code : 
------------------

<asp:Repeater ID="rImages" runat="server">
    <ItemTemplate>
        <li><a href='<%# "Images/" & ImageHandler.ashx?ID=" + Eval("TranID") %>' 
            class="highslide" onclick="return hs.expand(this)"><img src='<%# "Images/" & 
            ImageHandler.ashx?ID=" + Eval("TranID") %>' width="130" height="100" /></a></li>
    </ItemTemplate>
</asp:Repeater>

------------------
ASHX Code: 
------------------

public void ProcessRequest(HttpContext context)
{
    int tranId = Convert.ToInt32((context.Request.QueryString["ProductMasterID"]));

    if (tranId > 0)
    {
        var memoryStream = new MemoryStream();
        /*
        // Connect to database -- Here I am using LINQ to SQL architecture
         * 
         * var dataContext = new DatabaseDataContext(Classes.Constant.GetConnectionString());
         * var getImageName = dataContext.MapImage.Where(p => p.TranId == tranId).Single();
         * 
         * if (getImageName.ImageName.Trim() != "") 
         * {
         *    byte[] imageFile = (byte[])getImageName.Trim();
         *    memoryStream.Write(imageFile, 0, imageFile.Length);
              context.Response.Buffer = true;
            
              if (file.Length > 0)
              {
                 context.Response.BinaryWrite(imageFile);
                 memoryStream.Dispose();
              }
         * }
         */
    }
}

Hope you understand now how to bind images from database using Asp.net Handler. Stay tune!