Question

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?

Was it helpful?

Solution

You can use Repeater control's ItemDataBound event.

I would like to suggest to style with CSS which is easy to maintain than hard-coded the color from code behind code.

The following example use Panel control as a wrapper, so that it can be styled depending on the logic.

<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";    
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top