How do I count the number of custom controls I have on the page?
I have a page with 5 custom 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 custom control).
How do I count the user controls that are on my page?
EDIT
This is my content markup.
<asp:Content ID="cntMain" runat="Server" ContentPlaceHolderID="ContentMain">
source to share
EDIT: Replace my original out-of-base answer with the following.
You probably need to reinstall the controls in the controls (perhaps in the panel?).
http://msdn.microsoft.com/en-us/library/yt340bh4(v=vs.100).aspx
This example only detects controls contained in the Page object and controls that are direct children of the page. It does not find text boxes that are children of a control, which in turn is a child of a page. For example, if you added a Panel control to a page, the panel control will be a child of the HtmlForm control contained in the Page, and it will be found in this example. However, if you then added a TextBox control to the Panel control, the TextBox control will not display the text in the example because it is not a child of the page or a control that is a child of the page. A more practical application of walking is thusit would be to create a recursive method that you can call to control the controls by collecting each control as it occurs.
EDIT 2: Adding links to examples of recursive search in SO.
Example using LINQ: fooobar.com/questions/61365 / ...
Traditional example: fooobar.com/questions/135269 / ...
source to share
You only need to change what you are looking 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 tested and worked for me.
source to share