Accessing user controls’s constituent controls from a hosting web page
I’ve read that user control’s constituent controls can be accessed only by user control and thus web page that hosts this user control cannot receive the events, call methods or set properties of these contained controls.
But I’m not sure the above claim is true, since I was able to access ( from hosting web page ) ClickButton.Click event ( assume WebUserControl1 contains ClickButton control ):
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{开发者_运维问答
Button ClickButton = (Button)WebUserControl1.Controls[0];
ClickButton.Click += someClickHandler;
}
thanx
The entire page is a tree of controls. You can "browse" through this tree regardless of the parent of that control. For example from inside a user control you could go down to the parent, which could be another control, then further down to the page, then to the master page, and so on.
So yes, you are correct, it's not hidden to the point you can't access it, but it's not published either. In a similar way using reflection you could call private methods that you couldn't otherwise. Using certain tools you could access and change code that's already compiled; so nothing is really out of reach.
These boundaries are set and used to minimize complexity, not as an absolute wall that cannot be crossed.
You can expose the user control's properties (i.e. settings), controls, and events publicly which means you don't have to find the control within the usercontrol.
精彩评论