views:

1200

answers:

3

I need to place a user control into the template of a repeater control and reference data items from the repeater's datasource.

I tried (ignore the second cast which is specific to the CMS platform I'm using):

<%# ((EPiServer.Core.PageData)((RepeaterItem)Container.Parent.NamingContainer).DataItem)["PageName"]%>

But that throws back the following error: Unable to cast object of type 'ASP.usercontrols_searchcontrols_searchresult_ascx' to type 'System.Web.UI.WebControls.RepeaterItem'

Searchresult_ascx is another user control that contains the actual repeater.

A: 

It sounds like you have more parents in the hierarchy to get to the control desired. I often use the immediate window in debug mode to find the depth I have to back out OR use the Trace="True" on the web page and look at the control tree to see the hierarchy. From that you should be able to figure out your code to get at the proper parent control.

klabranche
+2  A: 

I would add a property on the usercontrol to hold the container - like this:

<asp:repeater ... >
  <my:usercontrol containerdata='<%# Container.DataItem %>' ... />
</asp:repeater>

And of course inside the user control databind to the PageData item you are passing along.

Allan Thraen
Hi Allan, I see you picked up on the EPiServer keyword. :) While I have the opportunity, thanks for the awesome blog - you saved my butt a few times.Anyway, I'm hoping for a more generic solution to this problem. To give you a bit of background, we've created a custom templated repeater control that we use for listing EPiServer pages. Basically each Page Type that is rendered through the control uses a custom template to allow that Page Type's custom properties to be rendered as required.
The problem is that at the moment the whole control is hard coded for each template. What I'm experimenting with, is to try to dynamically load a user control based on the Page Type name to render the Page Type's data, to avoid having to make code changes to the repeater class when new page types are added. Furthermore using a user control without any code-behind would also remove the need to compile and deploy these changes.This is something that I'm working on on the side at the moment, so when I have a chance I will explore the options further and post the results.
It sounds fairly straightforward to load a custom user control and attach it to a repeater based on the pagetype. I'd probably do that in code-behind (on the page, not the user control) to get full control and testability.
Allan Thraen
This fixed my problem as well. I had to use Eval("name") instead of using DataBinder.Eval for some reason, but it works now. Thanks!
Chris
A: 

I would add an OnItemDataBound event to the repeater and from there bind the appropriate data to the user control.

Greg B