[ASP.net 2] How to list all controls from a form ?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hello !

I have an .aspx page that use a master page.
I want to do a for each that list all controls on this page.
I have try something like:
foreach (System.Web.UI.Control wct in this.Controls)
But there are only one control returned, the ASP.Design_master control.
An idea ?
Thanks.
 
in page this.controls will return top level controls only,
i mean control which are placed inside say panel does not list in
this.controls collection.

to get all controls in your page used

hasControls property of control there in this.controls collection.

so that you can iterate through all controls in page.

regards
bharat
 
I have found that if I want to do that, I must my code on the master page and
refer to the ContentPlaceHolder.
For example, I have this on the master page:
<asp:ContentPlaceHolder id='MyCPH' runat='server'>
</asp:ContentPlaceHolder>
And I have this on my 'salve page' (lol ^_^):
<asp:Content ID="MyContent" ContentPlaceHolderID="MyCPH" Runat="Server">
....
</asp:Content>
If I want to list the controls of MyContent, I must put this on the master
page:
foreach (Control ctl in MyCPH.Controls){}

Now i'm looking for testing the type of the control (ctl)...

Thanks for the help.
 
Controls are in a hierarchy, and there is still a chance you will not
see all the control on the page. You have to inspect the Controls
collection of each control object, also. The Page contains a
MasterPage, the MasterPage contains an HtmlForm and a
ContentPlaceHolder, the ContentPlaceholder contains a Panel and a
DataGrid ... etc. etc. etc.
 
You can go through them recursively:
<PRE>
public static void ListControls(System.Web.UI.Control ctrl)
{
foreach(Control subCtrl in ctrl.Controls)
{
ListControls(subCtrl);

//DO YOUR ACTION HERE
}
}
</PRE>
And just call the ListControls with the Page object.

That should help.

Remy Blaettler
www.collaboral.com
 
Back
Top