Is there a better way to access controls in an ITemplate than FindControl()?
Asked Answered
V

1

5

When a control is added to an UpdatePanel, it can still be accessed from the code behind of the containing page. How is this achieved? Can custom control developers do the same?

In other words, if I develop a template control using the ITemplate Interface, is there a way to wire it up (like the UpdatePanel seems to) so that any controls contained within (declaratively) can be accessed from the containing page also?

Voltaic answered 10/2, 2010 at 14:34 Comment(0)
D
7

You can add a TemplateInstanceAttribute on your ITemplate property to achieve this, it has the effect of promoting the controls to page level:

[TemplateInstance(TemplateInstance.Single)]
public ITemplate AnonymousTemplate {
  get { ... }
  set { ... }
}

From MSDN:

The TemplateInstanceAttribute class allows you to mark a template property as one that allows single or multiple instantiations. A template that only allows a single instantiation can have the controls that are contained inside of it referenced. The ZoneTemplate property is an example of a property that can be instantiated only one time.

Debility answered 10/2, 2010 at 14:44 Comment(4)
Thanks Nick, this is useful information - I did not know about that. So, any insight into how an UpdatePanel allows the referencing of controls, even though you can have multiple UpdatePanel controls on a page?Voltaic
@Voltaic - Although you can have multiple UpdatePanel controls (or any ITemplate parent) in that case each one can only have 1 of that ITemplate child, e.g. with UpdatePanel you can't have 2 <ContentTemplate> within the same panel, so the controls within it wouldn't appear twice causing a duplicate ID issue in your page.Debility
I can't access my controls in my ITemplate Control. Can anyone send me an example?Vishinsky
I know this post is ancient but I have been wading through some legacy code and had to fix a custom control to access controls inside its template. This answer was excellent. Thanks.Jelks

© 2022 - 2024 — McMap. All rights reserved.