Get an ascx on a aspx
I have a UserControl that consists of a Parent and Child UserControls that is displayed on a aspx page. I need to get the instance of the Parent UserControls from the child controls. The Parent has a set of nested .net controls and in these nested controls the child UserControls are displayed so if I use this from a child UserControls
MyControl _myControl = (MyControl)this.Parent.Parent.Parent.Parent.FindControl("MyControl");
where (this) = the child control and (Parent.Parent.Parent.Parent) walks me back the tree to the real parent.
Thi开发者_Go百科s will get me there but there just seems to be a better way. Any suggestions?
An ascx
shouldn't know anything about its parent(s): that's a sign that it's too closely coupled to other classes. They might as well be one class.
One alternative is to follow the law of Demeter: figure out what this
(your user control) needs from MyControl
, make it a property, and let your aspx provide it rather than asking for it.
If you're using a master page, you can start from there and use the container id to find the control. It just depends what the control is closer to.
This might help: http://www.asp.net/master-pages/tutorials/control-id-naming-in-content-pages-cs
Another thing you can do if you're accessing a value from a control in a parent page, is to put that value into the HttpContext.Current.Items["MyControlValue"] on page load. That way your usercontrol can grab that value easily
精彩评论