1

I have an ItemTemplate within a Repeater. Here's my code (forgive the inline styling, I just threw this together):

     <asp:Repeater ID="Repeater1" runat="server">
            <ItemTemplate>
                <div style="background-color: Silver; border-style: solid; display: inline-block; float: left; margin: 5px; overflow: hidden;">
                    <div style="text-align: center">
                        <asp:Label ID="lblImage" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "image") %>'></asp:Label>
                    </div>
                    <div>
                        <%# DataBinder.Eval(Container.DataItem, "url") %>
                    </div>
                    <div style="text-align: center;">
                        <asp:HyperLink ID="requestLink" runat="server" Text="Original" NavigateUrl='<%# DataBinder.Eval(Container.DataItem, "requestUrl") %>'>
                        </asp:HyperLink>
                    </div>
                </div>
            </ItemTemplate>
        </asp:Repeater>

The output, currently, looks like this: enter image description here

Based on certain conditions within my program, I'd like to change the border color of the item template (Green, yellow, or red). Can I do this in the code behind?

4

1 回答 1

2

您可以使用Repeater 控件的ItemDataBound事件。

我想建议使用易于维护的 CSS 进行样式设置,而不是从代码后面的代码中硬编码颜色。

下面的示例使用 Panel 控件作为包装器,以便可以根据逻辑对其进行样式设置。

<asp:Repeater ID="Repeater1" runat="server" 
    OnItemDataBound="Repeater1_ItemDataBound">
    <ItemTemplate>
        <asp:Panel runat="server" ID="Panel1">
            <div style="text-align: center">
            <asp:Label ID="lblImage" runat="server" Text='<%# Eval("image") %>'/>
            </div>
            <div>
                <%# Eval("url") %>
            </div>
            <div style="text-align: center;">
                <asp:HyperLink ID="requestLink" runat="server" 
               Text="Original" NavigateUrl='<%# Eval("requestUrl") %>'>
                </asp:HyperLink>
            </div>
        </asp:Panel>
    </ItemTemplate>
</asp:Repeater>


protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || 
      e.Item.ItemType == ListItemType.AlternatingItem)
    {
        var panel1 = e.Item.FindControl("Panel1") as Panel;
        var rating = ((Evaluation) e.Item.DataItem).Rating;

        if (rating == "Good")
        {
            panel1.CssClass = "good";
        }
        else if (rating == "Bad")
        {
            panel1.CssClass = "bad";    
        }
    }
}
于 2013-10-11T17:33:32.003 回答