頁面可以被看成各種控制群組成的一個集合。在頁面被初始化和載入過程中,可以遍曆這些控制項,找到特定的控制項,或者改變某些控制項的屬性。
先看下面的一個例子:
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 the
<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>
這個例子列出頁面上所有的控制項,結果如下:
A List of the Controls in the Controls Collection
System.Web.UI.LiteralControl -
System.Web.UI.WebControls.Label - lblControlList
System.Web.UI.LiteralControl -
System.Web.UI.HtmlControls.HtmlForm -
System.Web.UI.ResourceBasedLiteralControl -
特別要注意的一點:以上代碼沒有列出ID=“txtName”的TextBox控制項!因為這個TextBox控制項包含在Form裡面,是Form的一個子控制項。而我們的代碼 foreach(Control c in Controls) 只關心當前頁面Controls的控制項,至於子控制項卻未能涉及。(可以把這些控制項理解成一個樹狀的層次關係)
頁面Controls
/ | \ //foreach(Control c in Controls)
控制項1 控制項2 控制項3 // 只判斷控制項1、2、3屬於頁面Controls
/ \ //而未涉及到下屬子控制項
子控制項1 子控制項2
為了真正做到遍曆所有控制項集,可以用遞迴的方法來實現:
<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) // 判斷該控制項是否有下屬控制項。
{
lblControlList.Text += "<ul>";
IterateThroughChildren(c); //遞迴,訪問該控制項的下屬控制項集。
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 the
<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>
以上代碼運行結果如下:
A List of the Controls in the Controls Collection
- 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
這下TextBox控制項真的露出了廬山真面目。