I realize that a whole lot of code cannot fit here, but I am asking for general direction or pointer.
I have .NET user controls nested six deep for an interactive gadget with (outer to inner) of : wrapper, tabs, panels, lists, rows, items.
I am trying to get a reference to an ancestor control from a nested control.
Specifically, I have this code in the code behind of a embedded ‘great great grand child’ control. It works, but it is very ugly:
MyTab _myTab = this.Parent.Parent.Parent.Parent.FindControl(thisTab) as MyTab;
which equals {ASP.controls_appname_widget_mywidget_mytab_ascx} and is correct.
I realize that I can do something like Page.FindControl(‘MyWrapper:MyPanel:etc…..) but that is not recommended either, since structure or IDs can change….
Is there a decent alternative?
Remember that components are best made ignorant. You never want any control to have any knowledge of anything above itself in the hierarchy and to have interface-only knowledge of controls below itself in the hierarchy. This architectural approach will save you much pain and suffering in the long run and will avoid situations like you are in now.
As for fixing the current problem the best way to fix it is to create a
MyTabmember in your control that is settable by parent controls. This is not a perfect solution as your control is not totally ignorant of others but at least you will no longer have to know how to get theMyTabreference – it will be provided to you.So I would create a property called something like
ParentTaband set this property equal to theMyTabreference somewhere in the page or inside a control that does and should have visibility to bothMyTaband your control.