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

孤街醉人 提交于 2019-12-05 21:47:41

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.

another option:

<tr class="<%# GetClassForPrice( Container.DataItem ) %>">

and in code-behind

protected string GetClassForPrice( object data ) 
{
    var rowOption = (Option)data;
    if(rowOption.Price > 100) return "red";
    else return "green";
}

also... any reason you're not using data binding? it would let you eliminate your ItemDataBound code-behind method.

<tr>
    <td class="GridRow"><%# Eval("Account") %></td>
    <td class="GridRow"><%# ((bool)Eval("Margin")) ? "Y" : "N" %></td>
    <td class="GridRow"><%# Eval("Symbol") %></td>
    <td class="GridRow"><%# Eval("Price", "{0:c}") %></td>
</tr>

use this code inside repeter databound event.

HtmlTableRow tr = (HtmlTableRow)e.Item.FindControl("trID"); 
tr.Visible = false;

Another option you can use is jQuery. Seeing you're using a repeater, that gives you full control over your output. Jquery can get into your table, look at the data and format it how you want it.

Look at: http://plugins.jquery.com/project/Plugins/category/54

http://plugins.jquery.com/project/Colorize

http://franca.exofire.net/js/demo_cross.html

Alternately you can use the Code behind in the repeater to set the CSS Class of the cells/rows/columns you need changed.

You'll need to make those controls server controls (require: ID="my_thing" runat="server"), create those controls (use the find control and bind them), then set the CSS class after you determine the value.

Bruce Allen

Dave Thieben's answer works nicely, except that the css is missing.

If you add the following then the example will work:

table tr.red td { background-color:red; }
table tr.green td { background-color:green; }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!