ASP.NET repeater alternate row highlighting without full blown <alternatingitemtemplate/>

*爱你&永不变心* 提交于 2019-11-28 16:48:31

There is no need to manage your own variable (either an incrementing counter or a boolean); you can see if the built-in ItemIndex property is divisible by two, and use that to set a css class:

class="<%# Container.ItemIndex % 2 == 0 ? "" : "alternate" %>"

This has the benefit of being completely based in your UI code (ascx or aspx file), and doesn't rely on JavaScript.

C#

class="<%# Container.ItemIndex % 2 == 0 ? "" : "alternate" %>"

VB

class="<%# iif(Container.ItemIndex Mod 2 = 0,"","alternate") %>"

This helped me

class='<%# Container.ItemIndex % 2 == 0 ? "" : "alternate" %>'

Previous answer resulted in "Server Tag is not well formed" error.

Apply the classes with JQuery.

$('.divtable > div:odd').addClass('dark');
$('.divtable > div:even').addClass('light');
Keith Bloom

You could use jQuery instead. This answer to a previous question may help: jQuery Zebra selector

Little tweak: the empty class could be removed with something like:

  <%# Container.ItemIndex % 2 == 0 ?  "<tr>" : "<tr class='odd'>"  %>

IsAlternatingRow can be a protected property and will get set in the ItemDataBound or ItemCreated event.

protected void rpt_ItemDataBound(object sender, EventArgs e)
{
    IsAlternatingRow = !IsAlternatingRow;
}

No need for code. Here's a pure CSS solution:

.item:nth-child(odd){background-color: #ccc}
.item:nth-child(){background-color: #ddd}

https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child

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