Search code examples
asp.netasp.net-ajaxasp.net-2.0code-behind

Finding a dynamically added control on an aspx page


I have an asp page "A" and I've created a user control "B"

When I do A.Controls.Add(B), I would like to make an element, say a TableRow which is defined inside control "B", invisible via code behind.

When looking through Controls of "A", I cannot seem to find that table row.

Any hints?

I'm sure it is something really simple I'm missing.

Thank you.


Solution

  • You should expose the controls that are modifiable and accessible from outside as properties. MSDN

    But consider not to expose the whole control itself but only f.e. a Text-Property of a Textbox, because that prevents from unintentional and unpredictable behaviour. A usercontrol should encapsulate complexity and should be (mostly) reusable. The more control you offer to the controls(f.e. the page) that use the usercontrol, the less reusable and the more error-phrone they are.

    If you for example have built a Login-Control with a Textbox for the Username and a Textbox for the Password, it makes sense to offer properties named Username and Password instead of returning the Textboxes itself. The properties each return the respective Textbox-Text value.

    In your example with the TableRow, what is its purpose? You should expose a property with a meaningful name to control its visibility(f.e. ShowTitle if the row contains a title, the getter/setter would return/set the actual tablerow's visible state).

    Of course you need a reference to your UserControl if you want to access its properties. You should provide sourcecode if you have problems on finding it on the page. It depends on where you have created and added it. Normally you will find controls with FindControl on the NamingContainer (f.e. the NamingContainer of a control defined in a GridView's TemplateColumn is the GridViewRow itself).