Pages can be seen as a collection of various controls. During page initialization and loading, You can traverse these controls to find specific controls or change the properties of some controls.
Let's take a look at the following example:
Script runat = "server" language = "C #">
Void Page_Load (Object sender, EventArgs e)
{
Foreach (Control c in Controls)
LblControlList. Text + = c. ToString () + "-" + c. ID + "<br> ";
}
</Script>
<Html>
<Head>
</Head>
<Body>
<B> A List of the Controls in
<Code> Controls </code> Collection </B> <br>
<Asp: label runat = "server" id = "lblControlList"/>
<P>
<Form runat = "server">
What's your name?
<Asp: textbox runat = "Server" id = "txtName"/>
</Form>
</Body>
</Html>
This example lists all the controls on the page. The result is as follows:
A List of the Controls inControlsCollection
System. Web. UI. LiteralControl-
System. Web. UI. WebControls. Label-lblControlList
System. Web. UI. LiteralControl-
System. Web. UI. HtmlControls. HtmlForm-
System. Web. UI. ResourceBasedLiteralControl-
Note: The above Code does not list the TextBox Control with ID = "txtName! This TextBox Control is included in Form and is a child control of Form. Our code foreach (Control c in Controls) only cares about the Controls Control on the current page, but does not involve the subcontrol. (These controls can be understood as a tree-like hierarchy)
Page Controls
/| \ // Foreach (Control c in Controls)
Control 1 Control 2 Control 3 // only Controls 1, 2, and 3 belong to page Controls
/\// Subcontrol not involved
Child Control 1 child Control 2
To truly traverse all the control sets, we can use recursive methods:
<Script runat = "server" language = "C #">
Void IterateThroughChildren (Control parent)
{
Foreach (Control c in parent. Controls)
{
LblControlList. Text + = "<li>" + c. ToString () + "</li> ";
If (c. Controls. Count> 0) // checks whether the control has any subordinate Controls.
{
LblControlList. Text + = "<ul> ";
IterateThroughChildren (c); // recursive, access the control's subordinate control set.
LblControlList. Text + = "</ul> ";
}
}
}
Void Page_Load (Object sender, EventArgs e)
{
LblControlList. Text + = "<ul> ";
IterateThroughChildren (this );
LblControlList. Text + = "</ul> ";
}
</Script>
<Html>
<Head>
</Head>
<Body>
<B> A List of the Controls in
<Code> Controls </code> Collection </B> <br>
<Asp: label runat = "server" id = "lblControlList"/>
<P>
<Form runat = "server">
What's your name?
<Asp: textbox runat = "Server" id = "txtName"/>
</Form>
</Body>
</Html>
The running result of the above Code is as follows:
A List of the Controls inControlsCollection
- System. Web. UI. LiteralControl
- System. Web. UI. WebControls. Label
- System. Web. UI. LiteralControl
- System. Web. UI. HtmlControls. HtmlForm
- System. Web. UI. LiteralControl
- System. Web. UI. WebControls. TextBox
- System. Web. UI. LiteralControl
- System. Web. UI. ResourceBasedLiteralControl
The TextBox Control really shows its true face.