Datalist Image

Was once wondering how to get images from the database and display it in a datalist control or a datagrid control in ASP.NET, and came across the following probable solution (alternate ideas on this would be appreciated ).

Steps:

1.Get the image from the database and store it temporarily on the server side.
2.Set the ImageUrl property of the Image control to the temporary path.

Coding goes something like this,

aspx Page:

Datalist control included a image control and a label control to hold description.


<asp:DataList ID="DataList1" runat="server" >
        <ItemTemplate>
            <asp:Image ID="Image1" runat="server" Width="50" Height="50"/>
            <asp:Label ID="Label1" runat="server" ></asp:Label>
        </ItemTemplate>
</asp:DataList>

now when binding the grid to the database,

it would have been straightforward if at all path of the image was stored in the database

<asp:DataList ID="DataList1" runat="server" >
        <ItemTemplate>
            <asp:Image ID="Image1" runat="server" Width="50" Height="50" ImageUrl='<%# Eval("imagePathColumnname") %>'/>
            <asp:Label ID="Label1" runat="server" Text='<%# Eval("Description") %>'></asp:Label>
        </ItemTemplate>
</asp:DataList>



 in our case we have to get raw image from the database so solution would be



<asp:DataList ID="DataList1" runat="server" onitemdatabound="DataList1_ItemDataBound">
        <ItemTemplate>
            <asp:Image ID="Image1" runat="server"  Width="50" Height="50"/>
            <asp:Label ID="Label1" runat="server" Text='<%# Eval("Description") %>'></asp:Label>
        </ItemTemplate>
</asp:DataList>

Code Behind Event ItemDataBound



protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        Image img = (Image)e.Item.FindControl("Image1");
        byte[] imgbytarr = ((e.Item.DataItem as DataRowView).Row["imgCol"] as byte[]);
        
        string imgpath = Server.MapPath("~/Images/" + (e.Item.DataItem as DataRowView).Row["MasterId"].ToString() + ".jpg");
        System.IO.FileStream fs = new System.IO.FileStream(imgpath,System.IO.FileMode.OpenOrCreate);
        fs.Write(imgbytarr, 0, imgbytarr.Length);
        fs.Close();
        img.ImageUrl = "~/Images/" + (e.Item.DataItem as DataRowView).Row["PrimaryKey"].ToString() + ".jpg"
    }


download code

Comments

Popular posts from this blog

Launch .Net Core with VSCode for starters

Google Maps

Protecting sensitive data using Secret Manager in .Net Core