Sunday, April 26, 2009

Finding All Controls on Page in Asp.net

To find all controls on Page, including child controls. i.e. Loop through all control list.

Example: I have a page with Controls on Page, Pannel Controls (Which contains Few more child controls). Now I want to find list of all controls on Page including child control.

private void ListControlCollections()
    {
        ArrayList controlList = new ArrayList();
        AddControls(Page.Controls,controlList);

        foreach (string str in controlList)
        {
            Response.Write(str + "
");
        }
        Response.Write("Total Controls:" + controlList.Count);
    }

    private void AddControls(ControlCollection page,ArrayList controlList)
    {
        foreach (Control c in page)
        {
            if (c.ID != null)
            {
                controlList.Add(c.ID);
            }
           
            if(c.HasControls())
            {
                AddControls(c.Controls, controlList);
            }
        }
    }

No comments: