Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count the number of user controls that I have in a page?

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">
like image 689
Richard77 Avatar asked Nov 25 '25 07:11

Richard77


1 Answers

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.

like image 110
Aristos Avatar answered Nov 27 '25 23:11

Aristos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!