Tuesday, 22 December 2009

Changing the last item in a repeater

You can't change the last item of a repeater in its itemDataBound event, as there is no way of knowing you are on the last item. The concept you need to follow is that you poke it later on during the preRender event of either the repeater or the page.

I needed to do this, but I had an extra complication - I was working with a nested repeater in a page that had a master page. The fact that this was a child page made finding my control a bit of a pain using Page preRender, so I thought it would be sensible to use the preRender event of the parent repeater. To my surprise while debugging I discovered that my parent repeater's preRender event was firing before the child or nested repeaters had even started binding. Weird.

So, in the end, I used the child repeater's preRender event. In this I look for the parent repeater, and loop through its repeater items looking for my nested repeater (which I'm about to render). Then I find my control and make the change I want.


protected void ChildRepeater_PreRender(object sender, System.EventArgs e)

   Repeater ParentRepeaterRpt = (Repeater)ContainerofParent.FindControl("ParentRepeater");

    foreach (RepeaterItem item in ParentRepeaterRpt.Items)
        Repeater ChildRepeaterRpt = (Repeater)item.FindControl("ChildRepeater");
        if (ChildRepeaterRpt.Items.Count > 0)
            RepeaterItem rptItem = ChildRepeaterRpt.Items[ChildRepeaterRpt.Items.Count - 1];

            Literal MyLit = (Literal)rptItem.FindControl("MyLitName");
            MyLit.Text = "whatever";


No comments:

Post a Comment

Comments are moderated, so you'll have to wait a little bit before they appear!