Search code examples
c#asp.netasprepeater

Set AlternateItemTemplate Manually


Is there a way to set AlternateItemTemlate manually? I suffered from this question more than once.

I want to use it only for the last item. Maybe ItemDataBound event can be a solution but i can not figured out.

Only useful questions that I've found:


Solution

  • The ItemDataBound is indeed a possible option, but for it to work, you would need the total count of the repeater items, so you can identify the last item:

    protected void rptDummy_OnItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        int itemsCount = ((List<SomeClass>)rptDummy.DataSource).Count;
    
        if (e.Item.ItemType == ListItemType.Item)
        { 
            if(e.Item.ItemIndex == itemsCount - 1)
            {
                //Do Things here
            }
        }
    }
    

    You could even have two placeholders within the same template, one specially for the last item:

    <ItemTemplate>
        <asp:PlaceHolder id="phIsNotLastOne" runat="server">Is not last</asp:PlaceHolder>
        <asp:PlaceHolder id="phIsLastOne" runat="server">Is last</asp:PlaceHolder>
    </ItemTemplate>
    

    Then you could do something like this:

    protected void rptDummy_OnItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        long itemsCount = ((List<SomeClass>)rptDummy.DataSource).Count;
    
        if (e.Item.ItemType == ListItemType.Item)
        { 
            PlaceHolder phIsLastOne = (PlaceHolder)e.Item.FindControl("phIsLastOne");
            PlaceHolder phIsNotLastOne = (PlaceHolder)e.Item.FindControl("phIsNotLastOne");
            phIsLastOne.Visible = e.Item.ItemIndex == itemsCount - 1;
            phIsNotLastOne.Visible = !this.phIsLastOne.Visible;
        }
    }