|Important||This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer|
How to: Locate the Web Forms Controls on a Page by Walking the Controls Collection
Every container control on the page, and the page itself, has a Controls collection that you can use to get to individual controls.
To locate controls in the Controls collection
Loop through the Controls collection of the container control. The collection is of type, and returns objects of type .
The following example illustrates how to walk the Controls collection. The example assumes an ASP.NET Web page with at least onecontrol on it, a control, and a control. The code gets all the child controls of the object. Because this would produce only a few high-level child controls, including the object, the code also walks the Controls collection of each individual 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 acontrol 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.
Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim allTextBoxValues As String = "" Dim c As Control Dim childc As Control For Each c In Page.Controls For Each childc In c.Controls If TypeOf childc Is TextBox Then allTextBoxValues &= CType(childc, TextBox).Text & "," End If Next Next If allTextBoxValues <> "" Then Label1.Text = allTextBoxValues End If End Sub