ASP.NET如何取得網頁上所有控制項的Type?

小弟在最近看到有人這樣寫..就把它分享出來...

小弟在最近看到有人這樣寫..就把它分享出來...

asp.net(c#)

ControlCnt.aspx

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Control</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            <asp:Button ID="Button1" runat="server" Text="Button" />
            <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
            <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
            <asp:Panel ID="Panel1" runat="server" Height="50px" Width="125px">
                <asp:Button ID="Button2" runat="server" Text="Button" />
                <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox></asp:Panel>
        </div>
    </form>
</body>
</html>

ControlCnt.aspx.cs

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 ControlCnt : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        showControl(this.Page);
    }


    protected void showControl(Control controls)
    {
        foreach (Control ctl in controls.Controls)
        {
            Response.Write(ctl.GetType() + "<br/>");

            if (ctl.HasControls())
            {
                showControl(ctl);
            }

        }

    }

}

執行結果: