Controlling a Usercontrol from another Usercontrol

Posted Friday, May 14, 2004 4:46 PM by CumpsD
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:
1private void cmdMakeVis_Click(object sender, System.EventArgs e) { 
2 TestSite.DefaultPage Default = (DefaultPage)Context.Handler;
3 TestSite.Control2 UserControl2 = (Control2)Default.FindControl("UControl2");
4 if (UserControl2 != null) {
5 UserControl2.Visible = true;
6 }
7} /* cmdMakeVis_Click *
I also uploaded this small test project as an illustration.
Filed under:

Comments

# re: Controlling a Usercontrol from another Usercontrol

Friday, May 14, 2004 11:04 AM by Gokhan Altinoren

This reminds me an article for IBuySpy module communication by Brian Bilbro:
http://authors.aspalliance.com/bbilbro/viewarticle.aspx?paged_article_id=6

# re: Controlling a Usercontrol from another Usercontrol

Friday, May 14, 2004 11:14 AM by David Cumps

Number 2 of that page (Have a base page class coordinate the communication) is my preffered approach, user controls are simply small modules you can control from your pages.

Pages control usercontrols.
Usercontrols don't control usercontrols.

(I know they can, and a usercontrol can have another usercontrol on it, but you get my point ;))

Very nice page btw, just bookmarked it, if I have to make a communication system between classes later :)

# re: Controlling a Usercontrol from another Usercontrol

Friday, May 14, 2004 12:23 PM by AndrewSeven

How about using interfaces...

# re: Controlling a Usercontrol from another Usercontrol

Friday, May 14, 2004 6:26 PM by Wilco

Or <a href="http://wilcoding.xs4all.nl/Wilco/Articles/View.aspx?NodeID=136">connection points or meta-data based connection points</a>? ;).