Search code examples
c#htmlasp.netrepeater

How can I set a table row color in my repeater based on the values databound to that row in ASP.NET?


I have a repeater control:

 <table style="width: 100%">
     <asp:Repeater runat="server" ID="rptOptions" OnItemDataBound="rptOptions_ItemDataBound">
                                <HeaderTemplate>
                                    <tr>
                                        <td class="GridHeader">Account</td>    
                                        <td class="GridHeader">Margin</td>  
                                        <td class="GridHeader">Symbol</td>  
                                        <td class="GridHeader">Price</td> 
                                    </tr>
                                </HeaderTemplate>
                                <ItemTemplate>
                                    <tr>
                                        <td class="GridRow"><asp:Label runat="server" ID="lblOptionAccount"></asp:Label></td>
                                        <td class="GridRow"><asp:Label runat="server" ID="lblOptionMargin"></asp:Label></td>
                                        <td class="GridRow"><asp:Label runat="server" ID="lblOptionSymbol"></asp:Label></td>
                                        <td class="GridRow"><asp:Label runat="server" ID="lblOptionPrice"></asp:Label></td>
                                    </tr>
                                </ItemTemplate>
                             </asp:Repeater>
                        </table>

And the following code-behind databound method:

protected void rptOptions_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                Option rowOption = (Option)e.Item.DataItem;

                ((Label)e.Item.FindControl("lblOptionAccount")).Text = rowOption.Account;
                ((Label)e.Item.FindControl("lblOptionMargin")).Text = rowOption.Margin ? "Y" : "N";
                ((Label)e.Item.FindControl("lblOptionSymbol")).Text = rowOption.Symbol;
                       ((Label)e.Item.FindControl("lblOptionPrice")).Text = rowOption.Price.ToString("C", currencyFormat);

            }
        }

There are more columns in that grid, but I've slimmed it down just for the question.

Now, what I would like to do is change the tr's background color based on the price amount. If it is within different levels, I would like to change the rows background color correspondingly.

Do I have to do this with javascript or is there some way I can get access to the table rows in the code-behind to set this color?


Solution

  • make it to runat="Server"

    <tr runat="server" ID="trHeader"></tr>
    

    Then find that Table Row in by ID in your code behind in databound event, like what you are doing for other server side control and change color.