Show images in Repeater control

2019-08-11 11:11发布

问题:

I have the following List:

private List<System.Web.UI.WebControls.Image> _searchResultList = new List<System.Web.UI.WebControls.Image>();

This List may contain several Images with different URLs.

I have the following Repeater:

<asp:Panel ID="SearchPanel" runat="server" ScrollBars="Vertical">
    <asp:Repeater ID="Repeater" runat="server">
        <ItemTemplate>
            <asp:Image height="32" width="32" runat="server"/>
        </ItemTemplate>
    </asp:Repeater>
</asp:Panel>

Using DataSource to display the images doesn't seem to work.

Repeater.DataSource = _searchResultList;           
Repeater.DataBind();

What am I doing wrong?

回答1:

The _searchResultList is not a list of strings so you can't use ImageURL='<%Container.DataItem.ToString()%>'. Because _searchResultList is a list of images you should bind the ImageUrl property. This should works fine for you:

<asp:Repeater ID="Repeater" runat="server">
    <ItemTemplate> 
       <asp:Image ID="Image1" height="32" width="32" runat="server" ImageUrl='<%# Eval("ImageUrl") %>' /> 
    </ItemTemplate>
</asp:Repeater>

In this example Container.DataItem refers to an Image control. This is why we used Eval("ImageUrl") to get the ImageUrl property of each Image control.



回答2:

        <asp:Panel ID="SearchPanel" runat="server" crollBars="Vertical">
        <asp:Repeater ID="Repeater" runat="server">
         <ItemTemplate>
            <asp:Image height="32" width="32" runat="server" ImageURL='<%Container.DataItem.ToString()%>'/>// changes here
        </ ItemTemplate>
           </asp:Repeater>
            </asp:Panel>