Is there any way to find out the count of controls used in each page of an ASP.Net application? Please help
Asked
Active
Viewed 108 times
1 Answers
1
Why do you need it? Define controls first, everything that derives from System.Web.UI.Control
?
You could write a recursive extension method which which returns all controls lazily, then it is simple:
protected void Page_PreRender(object sender, EventArgs e)
{
var allControls = this.GetControlsRecursively().ToList();
}
Here a possible implementation:
public static class ControlExtensions
{
public static IEnumerable<Control> GetControlsRecursively(this Control parent)
{
foreach (Control c in parent.Controls)
{
yield return c;
if (c.HasControls())
{
foreach (Control control in c.GetControlsRecursively())
{
yield return control;
}
}
}
}
}

Tim Schmelter
- 450,073
- 74
- 686
- 939
-
Minor point: instead of `c.Controls.Count > 0`, use [`c.HasControls`](http://msdn.microsoft.com/en-us/library/system.web.ui.control.hascontrols.aspx) - should be slightly faster – Hans Kesting Feb 15 '13 at 08:40
-
@HansKesting: Thanks, edited it accordingly. But i assume that performance is not the reason why we should prefer `HasControls`. Touching the `Controls` property recursively will cause the ViewState to be loaded if not already done for all controls, that can cause side effects. http://stackoverflow.com/a/5278825/284240 – Tim Schmelter Feb 15 '13 at 08:45