I have a asp.net repeater control in a aspx page, with runat=”server” and an id set, however for some reason i can’t access its ID from code behind (I can access the id of the asp:detaislview control it sits in though). So instead in the page_load method I am doing the following:
Repeater repeater = (Repeater)PromotionSitesDetailsView.FindControl("estateRepeater");
repeater.DataSource = estateList;
However when run, an error comes up saying the repeater is null! All I want to do is set the datasource of this repeater to a List object. Any ideas?
You said the Repeater sits inside a DataList. The DataList is, itself, a kind of repeater – the controls inside of it don’t exist until the DataList is bound to a datasource, and the controls in the template are created once per item in the source. So if you bind the DataList to a source with 3 items, you will get 3 repeaters.
So it looks kind of like this:
So obviously
MyDataList.FindControl("MyRepeater")can’t work – which “MyRepeater” are we talking about? Since multiple controls cannot have the same ID, ASP.NET solves this by making the ID unique to something called a NamingContainer. Since the DataList repeats the same set of controls many times (once per item in the data source), each item in the DataList is a NamingContainer.We need to find the NamingContainer we know holds the instance of MyRepeater that we want:
You can iterate over the items in the DataList after it has been bound (of course, before it has been bound it has no items). You can also operate on a given item in the DataList as that item is being created: