How can I create alternating background colors for listview rows while only using ItemTemplate?

独自空忆成欢 提交于 2019-12-24 08:46:50

问题


How can I create alternating background colors for listview rows while only using ItemTemplate? I don't want to use AlternateTemplate because I would have to edit both of them everytime i want to change something when all I'm using it for is to create the alternating background colors. So what's a way I could do it using only the ItemTemplate? Thanks!


回答1:


If you could consider the alternating colours a progressive enhancement and not absolutely required in all (old) browsers then you could use a CSS n-th child selector to apply the colour without changing the HTML.

If you have jQuery (or similar) in your project already and want a solution for older browser, you could use that to select every other row with the :odd or :even selector.

Update (Example)

Assuming we are using table rows

tr:nth-child(odd) td{  
  background-color: red;  
}

You can also use even, 2n or 2n+1. This would work equally well with <li> tags.

More examples: http://reference.sitepoint.com/css/pseudoclass-nthchild




回答2:


This might work too:

Alternating Table Row Colors with ASP.Net ListView Control

It uses the <%# style syntax in your ASPX page to toggle the class based on the DisplayIndex Mod 2.

C# and VB code samples on that link too...




回答3:


Use the ItemDataBound event of the ListView (if it has one like the Repeater does). Add a runat="server" element to your ItemTemplate that you can use to set the color using a class. Get a reference to this control in the event and set the css class.




回答4:


Have you tried using a Repeater control, instead of the ListView.

You'll have more control over the template, and it's easier to change alternating colors, w/out having duplicate templates.



来源:https://stackoverflow.com/questions/8670708/how-can-i-create-alternating-background-colors-for-listview-rows-while-only-usin

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