Search code examples
c#asp.netrepeaterseparator

Detecting the last separator in a Data repeater


I am using a repeater (ASP.Net/C#) to show a list of names using a comma in the SeparatorTemplate. The problem is that I get a list that looks like this:

James, Bob, Joe, Frank

Whereas I would like to have something like:

James, Bob, Joe and Frank

How can I detect the last separator so that I can make it show " and " rather than ", "?

Thanks in advance.


Solution

  • You can count items and display "and" instead of "," for the last item. To test I have this markup:

    <asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_ItemDataBound">
        <ItemTemplate>
            <%# Container.DataItem %>
        </ItemTemplate>
        <SeparatorTemplate>
            <%# (Container.ItemIndex <((ArrayList)Repeater1.DataSource).Count  - 2?",":" and ") %>
        </SeparatorTemplate>
    </asp:Repeater>
    

    And my code:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ArrayList values = new ArrayList();
    
            values.Add("James");
            values.Add("Bob");
            values.Add("Joe ");
            values.Add("Banana");
            values.Add("Frank");
    
            Repeater1.DataSource = values;
            Repeater1.DataBind();
        }
    }
    

    And my output:

    enter image description here