Mega Code Archive

 
Categories / ASP.Net Tutorial / Page Lifecycle
 

Display all controls on a page

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.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>     <div>         <i>This is static HTML (not a web control).</i>     </div>     <form id="Controls" runat="server">     <div>             <asp:panel id="MainPanel" runat="server" Height="112px">             <asp:Button id="Button1" runat="server" Text="Button1"/>             <asp:Button id="Button2" runat="server" Text="Button2"/>             <asp:Button id="Button3" runat="server" Text="Button3"/>             <asp:Label id="Label1" runat="server" Width="48px">               Name:</asp:Label>             <asp:TextBox id="TextBox1" runat="server"></asp:TextBox>             </asp:panel>             <asp:Button id="Button4" runat="server" Text="Button4"/>          </div>     </form>     <div>         <i>This is static HTML (not a web control).</i>     </div> </body> </html> File: Default.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 ControlTree : System.Web.UI.Page {   private void Page_Load(object sender, System.EventArgs e)   {     DisplayControl(Page.Controls, 0);   }   private void DisplayControl(ControlCollection controls, int depth)   {     foreach (Control control in controls)     {       Response.Write(new String('-', depth * 4) + "> ");       Response.Write(control.GetType().ToString() + " - <b>" + control.ID + "</b><br/>");       if (control.Controls != null)       {         DisplayControl(control.Controls, depth + 1);       }     }   } }