The current project I'm working on allows UserControls to be dynamically added to a page in a number of different placeholders across what could be an infinite number of templates. So basically using a CMS.
Awesome I hear you say but what happens when I want two of these UserControls to talk to each other? i.e. A search form control and a search results control. This was the problem I tackled recently and came up with a solution I'm reasonably happy with but thought I'd float it out there and see what you all think.
Firstly, I quickly decided to ignore the FindControl method, any solution I could think of involving it got messy and made me die a little inside.
EDIT: The decision to not use FindControl is due to the fact it only searches through the Control's child control collection and thus would require looping through controls to find the one I want.
This is what I have so far: Added a global public property to my base page class called BasePage:
public SortedList<string, CustomUserControl> CustomControls { get; set; }
Added a public property to my base user control class called CustomUserControl:
protected SortedList<string, CustomUserControl> CustomControls
{
get
{
BasePage page = Page as BasePage;
if (page != null)
return page.CustomControls;
else
return null;
}
}
On the Page_Init of my UserControls added a reference to the control to the CustomControl collection, which assigns it to the property of the BasePage.
I can then access my UserControls from either the Page or the controls themselves using the CustomControl method, like such:
if (this.CustomControls.ContainsKey("SearchForm"))
searchForm = this.CustomControls["SearchForm"] as SearchForm;
Thats the basics of it, am refining it as write this so please feel free to pick it apart. If any of you have a better/alternative solution I'd love to hear it. Or even if you've read an article on the problem, Google didn't help me much in my searches.