I was amazed to find that Microsoft didn't put all controls in the Page.Controls collection. They have followed more of a hierarchy pattern, where a page control has other controls, which may have other controls, which... You get the idea. This makes sense, especially if you've created any server controls yourself. However, this dose make it a bit harder to loop through every control on a page. The below is what I came up with, and I would be interested to see others.
private Control[] GetControls(ControlCollection parent, ref ArrayList controls)
{
foreach (Control c in parent)
{
controls.Add(c);
if(c.Controls.Count > 0)
{
GetControls(c.Controls, ref controls);
}
}
return (Control[])controls.ToArray(typeof(Control));
}
...
ArrayList ar = new ArrayList();
Control[] ControlArray = GetControls(Page.Controls, ref ar);
2 comments:
The trouble with that is if you have a non-server control, like a TD, and that non server control has a child server control, then your code will not "catch" that control.
Example:
<form id="frmOne" runat="server">
<table>
<td>
<asp:label id="lblOne" runat="server"/>
</td></tr>
</table>
In the example above lblOne will not be iterated
Great, I just used your code. Thank you!
Post a Comment