0

I have a webform and would like to run a method to return a list of all of the control ID's from within the form so I can export the list into somewhere like Excel (copy and paste from another object is fine).

Heres an example of what I want to return:

lblName
lblAddress
txtEmail
ddlSelection

How can I go about doing this?

crthompson
  • 15,653
  • 6
  • 58
  • 80
connersz
  • 1,153
  • 3
  • 23
  • 64
  • Please search SO, as this question is asked many times. – OldProgrammer Jan 06 '14 at 16:25
  • @connersz, try this link: http://stackoverflow.com/questions/277646/finding-all-controls-in-an-asp-net-panel – Katie Kilian Jan 06 '14 at 16:30
  • I have seen this examples but I don't want to do something in particular with certain controls within another control. I actually want to list every control within the webform into something. – connersz Jan 06 '14 at 16:37
  • The first snippet in [the accepted answer](http://stackoverflow.com/questions/277646/finding-all-controls-in-an-asp-net-panel/277654#277654) on that linked question gets every control in the page's control hierarchy. All you need to do is loop through the values in the returned object and display them on your page somehow (in a repeater, doing "Response.Write" for each one, concatenate all the control IDs into a giant string and put them in a Label, etc). – Josh Darnell Jan 06 '14 at 17:34
  • cmd.prompt's recursive solution here is perhaps easier to understand than Cristian Libardo's yield-return solution (although the latter is definitely more elegant) – sh1rts Jan 06 '14 at 23:14

1 Answers1

2
// Create a method to loop through
// the control tree and record ids
public void GetAllControlIDs(Control c, List<String> ids)
{
    ids.Add(c.ID);
    if(c.HasControls())
        foreach(Control ch in c.Controls)
            GetAllControlIDs(ch, ids);
}

// Call your method and pass in the
// Form since your question asks for
// the Form controls
List<String> allControlIDs = new List<String>();
GetAllControlIDs(this.Page.Form, allControlIDs);

foreach (String id in allControlIDs)
    Console.WriteLine(id);
cmd.prompt
  • 954
  • 7
  • 14