關於遍歷頁面所有控件的方法 空间

ControlCollection 定义变量  controls   。這個是頁面所有控件的集合 ,controls 包含層次 每一層有各個控件(這裡我不知道一共是有兩層還是有多層。等下繼續研究,先寫一下再说) 。第0層 第一个是ctl00    第0層第二個就是 

這個也是第 0層的  frm .這個 子层次   包含空控件就会在这里显示。 如下的效果就是。(本人把控件类型改成ID了方便我识别)

下面是C#代码

using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

public partial class ControlTree : System.Web.UI.Page

{

    protected void Page_Load(object sender, System.EventArgs e)

    {

        // Start examining all the controls. 

        DisplayControl(Page.Controls, 0);

        // Add the closing horizontal line.

        Response.Write("<hr />");

    }

    private void DisplayControl(ControlCollection controls, int depth)

    {

        foreach (Control control in controls)

        {

            // Use the depth parameter to indent the control tree.

            Response.Write(new String('-', depth * 4) + "> ");

            // Display this control. 

            Response.Write(  depth+         control.ClientID.ToString() + " - <b>" +

              control.ID + "</b><br />");

            //if (control is LiteralControl)

            //{

            //    // Display the literal content (whitespace and all).

            //    string text = ((LiteralControl)control).Text;

            //    Response.Write("Text: " + Server.HtmlEncode(text));

            //}

            if (control.Controls != null)

            {

                DisplayControl(control.Controls, depth + 1);

            }

           

        }

    }

}

//下面是頁面代碼,需要的可以拿過來試一下。

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ControlTree.aspx.cs" Inherits="ControlTree" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head >

    <title>Controls</title>

</head>

    <body>    

        <p><i>This is static HTML (not a web control).</i></p>

        <form id="frm" method="post" runat="server">

        <div>

            <asp:panel id="MainPanel" runat="server" Height="112px">

            <p><asp:Button id="Button1" runat="server" Text="Button1"/>

            <asp:Button id="Button2" runat="server" Text="Button2"/>

            <asp:Button id="Button3" runat="server" Text="Button3"/></p>

            <p><asp:Label id="Label1" runat="server" Width="48px">

              Name:</asp:Label>

            <asp:TextBox id="TextBox1" runat="server"></asp:TextBox></p>

            </asp:panel>

            <p><asp:Button id="Button4" runat="server" Text="Button4"/></p>

        </div>

        </form>

        <p><i>This is static HTML (not a web control).</i></p>

    </body>

</html>

原文地址:https://www.cnblogs.com/jixinyu12345/p/4872665.html