asp.net.ph

Skip Navigation Links

Using the Controls Collection

Web Forms Server Controls   Programming Web Forms Server Controls   Accessing Server Controls Programmatically


The Control class and its derived classes ( including the Page class ) expose a Controls property that returns a ControlCollection.

This hierarchy allows you to walk the control tree programmatically to search for specific controls on a page, as well as to check the type of controls within the collection in order to access their properties.

To locate controls in the Controls collection

  • Loop through the Controls collection of the container control. The collection is of type ControlCollection, and returns objects of type Control.

The following example illustrates how to walk the Controls collection. The example assumes an ASP.NET Web page with at least one TextBox control on it, a Label control, and a Button control. The code gets all the child controls of the Page object.

Because this would produce only a few high-level child controls, including the HtmlForm object, the code also walks the Controls collection of each child control. The code looks for text boxes by comparing the type of each control. When it finds a text box, it gets the text box’s value and concatenates it into a string that is displayed at the end in a Label control.

This example finds only the controls contained in the Page object and the controls that are direct children of the page. It does not find text boxes that are children of a control that is in turn a child of the page.

For example, if you added a Panel control to page, the Panel control would be a child of the HtmlForm control contained by the Page, and it would be found in this example. However, if you then added a TextBox control into the Panel control, the TextBox control text would not be displayed by the example, because it is not a child of the page or of a control that is a child of the page.

A more practical application of walking the controls this way would be to create a recursive method that can be called to walk the Controls collection of each control as it is encountered. However, for clarity, the example below is not created as a recursive function.

See Also

Using the FindControl Method   Accessing a Control’s Naming Container



© 2025 Reynald Nuñez and asp.net.ph. All rights reserved.

If you have any question, comment or suggestion
about this site, please send us a note