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
+4
A:
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>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
KClough
2009-05-26 17:14:57
A:
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.
benjamin
2009-05-26 17:40:24
+2
A:
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>
Jason
2009-05-26 17:44:24