C# – How to add controls to ItemTemplate (Repeater) at run time


I'm desinging a rich repeater control which needs some controls (specifically just an unordered list) added to it at runtime.

The solution I've opted for is to inject the nesseccary markup, onInit, into the header, item and footer templates respectively.
I can get the templates out (using InstantiateIn) and then add the markup as needed, but I don't know a way to add the template back in to the repeater?

Best Solution

In the past I've simply handled the ItemDataBound Event and modified the current RepeaterItem with whatever I needed to do.


private void Repeater1_ItemDataBound(object Sender, RepeaterItemEventArgs e)
    // Make sure you filter for the item you are after
    if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
        PlaceHolder listLocation = (PlaceHolder)e.Item.FindControl("listPlaceHolder");
        var subItems = ((MyClass)e.Item.DataItem).SubItems;

        listLocation.Controls.Add(new LiteralControl("<ul>");

        foreach(var item in subItems)
            listLocation.Controls.Add(new LiteralControl("<li>" + item + "</li>"));

        listLocation.Controls.Add(new LiteralControl("</ul>");
Related Question