No more then a few paragraphs of things I want to archive (instead of try to remember)

Thursday, May 31, 2007

Loop through all controls on an ASP.NET Web Form


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);