Reputation: 127
Is there any way to get the count of the number of controls used on an ASP.Net page without creating an instance of the Page class ?
Upvotes: 0
Views: 1285
Reputation: 6524
Asp.net server side controls comes into existance only after you create the instance of the page. Unless you create the instance of page class there is no existance of the controls and hence there is no question of counting them.
From the description, I assume that you want to know how many controls might get created from a particular markup (i.e. xxx.aspx page html). I would suggest a couple of ideas for that, I have not used them myself but might work for you.
the aspx page essentially contains xml so you can open it as an xml document and count all the tags which has runat="server" set. This would give you counts of node which contains this attribute which are the server side controls
Read the content of aspx file and count the instance of particular string "runat=server" which will give you same results but in an easier way
Open the aspx page using html agility pack and do the same thing as you did in 1 and 2 above.
Essentially, you are inspecting the markup which can result in to a server side control when an instance of the page is created.
Remember here that controls which are dynamically created from code behind will not be counted, just those which are created using designer will be counted.
Upvotes: 1
Reputation: 17604
You could use a method like:
public int CountControls(Control top)
{
int cnt = 1;
foreach (Control c in top.Controls)
cnt += CountControls(c);
return cnt;
}
And call it like
CountControls(Page);
or even
int count =Page.Controls.Count;
Upvotes: 0