Reputation: 9959
i am trying to add a css-class to table cells based on the value of a third column
My markup is...
<ItemTemplate>
<tr id="row">
<td><%# DataBinder.Eval(Container.DataItem, "Won")%></td>
<td><%# DataBinder.Eval(Container.DataItem, "Lost")%></td>
<td><%# DataBinder.Eval(Container.DataItem, "Result")%></td>
</tr>
</ItemTemplate>
If the value of the Result
is 1, add an css-class to the Won
table cell.
If the value of the Result
is 2, add an css-class to the Lost
table cell
I tried using the ItemCreated
event of the repeater control and got totally lost!
Any thoughts please?
Upvotes: 2
Views: 5681
Reputation: 7943
You have to use repeater's ItemDataBound method.
EDIT:
When you want to change the class of <td>
, you have to add attribute runat="server"
to it. Your
markup may look like below:
<asp:Repeater ID="rptMyRepeater" runat="server" OnItemDataBound="rptMyRepeater_ItemDataBound">
<HeaderTemplate>
<table>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%# DataBinder.Eval(Container.DataItem, "Won") %> </td>
<td><%# DataBinder.Eval(Container.DataItem, "Lost") %> </td>
<td runat ="server" id="tdResult"><%# DataBinder.Eval(Container.DataItem, "Result") %>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
And code:
protected void rptMyRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
HtmlTableCell tdResult = e.Item.FindControl("tdResult") as HtmlTableCell;
if (DataBinder.Eval(e.Item.DataItem, "Result").ToString() == "1")
{
tdResult.Attributes["class"] = "Won";
}
else if (DataBinder.Eval(e.Item.DataItem, "Result").ToString() == "2")
{
tdResult.Attributes["class"] = "Lost";
}
}
}
Upvotes: 4