3

I have a page that has 5 user controls. I want to do more with them, but for now, I just want to count them using the following method.

void btnFormSave_Click(object sender, EventArgs e)
{
  int i = 0;
  ControlCollection collection = Page.Controls;
  foreach (Control ctr in collection)
  {
    if (ctr is UserControl)
    {
      i++;
    }
   }
}

When I debug this code, i = 1, and the control is the master page (I didn't know that the master page is a user control).

How do I count user controls that are on my page?

EDIT

This is my content placeholder markup.

<asp:Content ID="cntMain" runat="Server" ContentPlaceHolderID="ContentMain">
Richard77
  • 20,343
  • 46
  • 150
  • 252

2 Answers2

1

EDIT: Replacing my original, off-base answer with the following.

You probably need to recurse to controls within controls (perhaps into a Panel?).

http://msdn.microsoft.com/en-us/library/yt340bh4(v=vs.100).aspx

This example finds only the controls contained in the Page object and the controls that are direct children of the page. It does not find text boxes that are children of a control that is in turn a child of the page. For example, if you added a Panel control to page, the Panel control would be a child of the HtmlForm control contained by the Page, and it would be found in this example. However, if you then added a TextBox control into the Panel control, the TextBox control text would not be displayed by the example, because it is not a child of the page or of a control that is a child of the page. A more practical application of walking the controls this way would be to create a recursive method that can be called to walk the Controls collection of each control as it is encountered.

EDIT 2: Adding links to recursive control search examples on SO.

Example using LINQ: https://stackoverflow.com/a/253962/704808

Traditional example: https://stackoverflow.com/a/4955836/704808

Community
  • 1
  • 1
weir
  • 4,521
  • 2
  • 29
  • 42
1

You only need to change where you look for:

void btnFormSave_Click(object sender, EventArgs e)
{
  int i = 0;
  // here, look inside the form, and not on page.
  ControlCollection collection = Page.Form.Controls;
  foreach (Control ctr in collection)
  {
    if (ctr is UserControl)
    {
      i++;
    }
   }
}

I have tested and working for me.

Aristos
  • 66,005
  • 16
  • 114
  • 150