Displaying an Image with a DataList

Posted by David Wier on 04/2/10 | Code Samples

Sometimes, with a Datalist, it would be nice to actually display an image as one of the Data items. This sample uses a simple Access DataSource ID to do so, with an AccessDataSource Control, although it would be just as easy to use a SQLDataSource Control also. Again, this is done with no code behind whatsoever. Just make sure, that in the data table, you include a path (relative path) to the folder and the image for each of the files. In this case, I used ‘~/images/prodImages/’, along with the actual image filename for each item. The other fields, as you can see from the source below, are :
ProdName and Comments.

‘Eval’ is used for each of the field names, in that we’re dealing with a later version of ASP.Net, however, in earlier versions, (and technically, still), you might have used ‘Container.DataItem’

<%@Page Language="VB" %>
<html>
<head> 
    <title>Displaying an Image with a DataList </title>
</head>
<body>
    <form id="form1" runat="server"> 
    <asp:AccessDataSource ID="AccDS1" runat="Server"
        SelectCommand="SELECT id, ProdName, ImgPath, Comments From Products"
            DataFile=".\app_data\products.mdb"></asp:AccessDataSource> 
        <asp:DataList ID="MyDataList" runat="Server" DataSourceID="accDS1"> 
            <HeaderTemplate> 
                <table border="1"> 
            </HeaderTemplate> 
            <ItemTemplate> 
                <tr> 
                    <td colspan="2"> 
                        <font color="#000000"><b>ProdName : </b> 
                            <%# Eval("ProdName")%> 
            </td
        </tr> 
        <tr> 
            <td align="Left" valign="Top"> 
                <b>Comments: </b> 
                <br> 
                    <%# Eval("Comments")%> 
            </td> 
            <td align="Left" valign="Top"> 
                <asp:Image runat="server" ID="myImage" 
                    ImageUrl='<%# Eval("ImgPath")%>'> 
                </asp:Image> 
            </td> 
        </tr> 
        </ItemTemplate> 
        <FooterTemplate> 
            </table> 
        </FooterTemplate> 
    </asp:DataList> 
    </form>
</body>
</html>




































0 Comments

COMMENTS

Name:
URL:
Comment:

Comments are disabled for this article.