简体   繁体   中英

Unable to call an ASP.NET user control from another

I wish to access a user control's public property from another user control. But, I am not able to access one user control within another. Even after using the namespace 'ASP', I am only able to see the reference to the current user control.

However, in a page I am able to refer to all the user controls with the ASP namespace.

Am I missing something or it needs to be that way?

Update: Here the exact scenario -
I have two user controls A and B. Now both of them are being used on a Page Default.aspx. There is a public proprty on control A which holds the name of the control clicked within A. I wish to access this property in control B to make some decisions. With the suggestions gioven by you, I understand reaching to the control by FindControl method of the container page, but how do I cast it to control A to fetch the property value when I cannot get the reference of the control A in B?

Thanks for the help guys!

One user control should not know about another user control (with the exception of any contained child controls, of course). If ControlABC referenced ControlXYZ, then you could never use ControlABC on any page, unless that page also had an instance of ControlXYZ - it would significantly hurt your ability to re-use ControlABC.

One way to address this is to use events to "wire up" a connection between the two controls. That way, ControlABC doesn't have a strong dependency on ControlXYZ - it can be re-used easily, even on pages where there is no ControlXYZ. The page can manage the connection between the two controls, adding delegates on ControlXYZ to the events on ControlABC, so the two controls can communicate.

There are likely other techniques for allowing your controls to interact with each other without introducing strong dependencies, which may have pros and cons, compared to events/delegates. Other SO members will point them out, I'm sure.

That's exactly the way it needs to be.

In my mind, it seems like a bad idea to couple one User Control to another like that. There's no way to guarantee that both will be present on the page.

If there's no other way around it though, a User Control does have access to the Page. You can then use Page.FindControl to find the other User Control and access its public properties that way.

"namespace" is not the same as "scope": namespace is just a way to orden the class-definitions. Scope is what you variables (instances) you can see at a particular point in your code.

That other user control is on the same page? (if not, then it will not work at all). You will need to go from the current usercontrol up to the page. From there you can find that other usercontrol.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM