Controlling a Usercontrol from another Usercontrol

Today I received a question on how to make a usercontrol visible from another usercontrol. You could also see this as: "How could a usercontrol control everything from another usercontrol?"

Normally you wouldn't do this kind of stuff (at least not in my opinion). Usercontrols are to ASP.NET what modules were for VB6, and just like another class, they should function without knowing what's outside their borders, like small functional containers.

Let's take a look at this. First I created a normal page, Default.aspx, and I also made two usercontrols, Control1.ascx and Control2.ascx.

Control2.ascx only has a label, and Default.aspx contains the two usercontrols (named UControl1 and UControl2). Control1.ascx has a button on it, called cmdMakeVis.

First I tried making UControl2 as a public property in Default.aspx, and accessing it from UControl2 through there, unfortunately that gave me an object reference not set error.

My second attempt turned out fine though:

I took the Default.aspx page out of the Context.Handler and searched for UControl2 on it. If I would find it, I could control it. Good thing it worked ;)

Here's the code the button contains:

[csharp] private void cmdMakeVis_Click(object sender, System.EventArgs e) { TestSite.DefaultPage Default = (DefaultPage)Context.Handler; TestSite.Control2 UserControl2 = (Control2)Default.FindControl("UControl2"); if (UserControl2 != null) { UserControl2.Visible = true; } } / cmdMakeVis_Click [/csharp]

I also uploaded this small test project as an illustration.