
Controlling a UserControl from Another UserControl
Originally published on my old blog at cumps.be on May 14, 2004.
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 any other 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 exposing UControl2 as a public property in Default.aspx, and accessing it from UControl1 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 found it, I could control it. Good thing it worked ;)
Here’s the code the button contains:
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 */
I also uploaded this small test project as an illustration.
You May Also Like

Writing Secure ASP.NET Session (Dutch)
The slides and demo code of my (Dutch) talk on writing secure ASP.NET: cross-site scripting, SQL injection, hashing passwords and more.

Differences between PHP and ASP.NET
Answers to a forum question for PHP developers moving to ASP.NET with C#: quotes, output, operators, string formatting and arrays.

How This Blog Is Served
The machinery behind the words you're reading: Hugo, an unprivileged nginx, a strict CSP, and a deploy script.



