Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change repeater li item class if first or last

Tags:

c#

.net

asp.net

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 <%=?

like image 242
gruber Avatar asked Mar 10 '11 17:03

gruber


2 Answers

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> 
like image 141
Oleks Avatar answered Oct 11 '22 05:10

Oleks


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> 
like image 45
nelsestu Avatar answered Oct 11 '22 04:10

nelsestu