Como: localizar os controles de Web Forms em uma página percorrendo a coleção Controls
Every container control on the page, and the page itself, has a Controls collection that you can use to get to individual controls.
Para localizar controles na coleção Controls
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 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.Ele não encontrará caixas de texto que sejam filhos de um controle que já é filho da página.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.Entretanto, para maior clareza, o exemplo a seguir não é criado como uma função recursiva.
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
private void Button1_Click(object sender, System.EventArgs e) { string allTextBoxValues = ""; foreach (Control c in Page.Controls) { foreach (Control childc in c.Controls) { if (childc is TextBox) { allTextBoxValues += ((TextBox)childc).Text + ","; } } } if (allTextBoxValues != "") { Label1.Text = allTextBoxValues; } }