1

I have to list all controls on a page. I do it like so

protected void listControls(Control c)
{
    if (c.HasControls())
    {
        tb_message.Text += String.Format("{0}{1}", c.ID, System.Environment.NewLine);
        foreach (Control control in c.Controls)
        {
            tb_message.Text += String.Format("{0}{1}", control.ID, System.Environment.NewLine);
            listControls(control);
        }
    }
}

Why is the output like this (+ an extra two empty lines at the beginning)

    form1

    tb_life_cycle

    tb_message

    btn_button

If I only have the following controls: tb_life_cycle, tb_message, btn_button + the form form1? Thank you

luca.p.alexandru
  • 1,660
  • 5
  • 23
  • 42

1 Answers1

0

ASP.NET Web Forms adds several controls to a Control collection so that it can render things like plain text (defined as part of the ASPX designer.) You'll probably find that the extra controls you weren't expecting as part of your output are LiteralControls generated by ASP.NET.

Try also including the Type of each control as part of your output.

protected void listControls(Control c) {
    if (c.HasControls()) {
        litText.Text += String.Format("{0}{1}{2}", c.GetType(), c.ID, System.Environment.NewLine);
        foreach (Control control in c.Controls) {
            litText.Text += String.Format("{0}{1}{2}", control.GetType(), control.ID, System.Environment.NewLine);
            listControls(control);
        }
    }
}
Red Taz
  • 4,159
  • 4
  • 38
  • 60