Server_Mule
Server_Mule

Reputation: 589

ASP.Net Repeater control

I've been trying everything I know to change the color of a row in an asp:repeater control. What I'm trying to do is this: Based on a value, I want to be able to set the color of a record in the repeater control. I've tried DIV tags, can't make it work. How do I go about this? Thaks

Upvotes: 1

Views: 3793

Answers (3)

Jason
Jason

Reputation: 28590

Use the <%# %> databinding syntax within the ItemTemplate to do conditional formatting:

<asp:Repeater runat="server" ID="rpt">
  <ItemTemplate>
    <div class="<%# Container.ItemIndex % 2 ? "even" : "odd" %>">
    </div>
    <div class="<%# Eval("PropertyOfDataSource") %>">
    </div>
  </ItemTemplate>
</asp:Repeater>

Upvotes: 5

benjamin
benjamin

Reputation: 1087

You could solve this a lot of different ways and depending on what your repeater needs to look like or the data you are sending to it there is no best answer. Here is a hack workaround that will evaluate the data and compare it for the proper color response.

In the item template of the repeater surround it by a div.

<div style="background-color:<%# GetBG((string)(DataBinder.Eval(Container.DataItem,"DataField")))%>">

and in the code behind have a function to decide

public string GetBG(string demo)
    {

        if (demo == "TestData2")
            return "yellow";
        return "Green";
    }

This isn't a very good way to do it and quite wasteful. An onDataBind function would be the better way to go, just wanted to show yet another way to accomplish this task.

Upvotes: 0

KClough
KClough

Reputation: 2089

Try something like this in the code behind

  protected void rpt_OnItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.DataItem != null)
        {
            string color = (string)DataBinder.Eval(e.Item.DataItem, "RowColor");
            HtmlTableRow rowToColor = (HtmlTableRow)e.Item.FindControl("Row");
            rowToColor.Attributes.CssStyle.Add("background-color", color );
        }
    }

and something like this in the aspx page

<asp:Repeater ID="rpt" runat="server" OnItemDataBound="rpt_OnItemDataBound">
    <ItemTemplate>
        <tr id="Row" runat="server">
            <td>
            &nbsp;
            </td>
        </tr>
    </ItemTemplate>
</asp:Repeater>

Upvotes: 4

Related Questions