I'm using repeater to create dynamic ul li list
Is it possible to control class whether item is first or last?
Something like:
class="<%# if(Container.ItemIndex == 0) { class = ... } ) %>"
by the way what does it really mean: <%#
in ASP.NET
What is the difference between <%#
and <%=
?
It is quite easy to determine whether the item is first or not (Container.ItemIndex == 0
), but to determine whether the element is last or not you have to use a custom property which will be initialized right with data binding:
protected int ItemCount { get; set; }
Here is a repeater example:
<asp:Repeater runat="server" ID="repeater"> <HeaderTemplate> <ul> </HeaderTemplate> <ItemTemplate> <li class="<%# GetItemClass(Container.ItemIndex) %>"> <%# Container.DataItem %> </li> </ItemTemplate> <FooterTemplate> </ul> </FooterTemplate> </asp:Repeater>
here is an example of data binding:
public override void DataBind() { var data = new string[] { "first", "second", "third" }; this.ItemCount = data.Length; repeater.DataSource = data; repeater.DataBind(); }
and finally a helper method:
protected string GetItemClass(int itemIndex) { if (itemIndex == 0) return "first"; else if (itemIndex == this.ItemCount - 1) return "last"; else return "other"; }
This will produce:
<ul> <li class="first"> first </li> <li class="other"> second </li> <li class="last"> third </li> </ul>
I typically use something like the following:
<asp:Repeater ID="rptItems" runat="server" ViewStateMode="Disabled"> <ItemTemplate> <li<%# Container.ItemIndex == ((IList)((Repeater)Container.Parent).DataSource).Count-1 ? " class='last'" : ""%>> ... </li> </ItemTemplate> </asp:Repeater>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With