May 18 2006

Looping Through Page Controls

Category: ASP.NET 1.x | ASP.NET 2.0 - GeneralBil@l @ 11:41

A very common question on the ASP.NET forums, is how to loop through the page controls, and find dynamically my control!

Here is the solution, its R E C U R S I O N !!

A very simple example, that loops through the page controls, and once it finds a Panel, it prints out, I am a Panel

 

    public void ShowPanels(Control p_Control)
    {
        try
        {
            // If control found is of type Panel
            if (p_Control.GetType().FullName.Equals("System.Web.UI.WebControls.Panel"))
            {
                                Response.Write ("I am a Panel!");
            }

            // Looping through all controls
            foreach (Control _control in p_Control.Controls)
            {
               ShowPanels(_control);
            }
        }
        catch (Exception ex)
        {
            throw new ApplicationException(ex.ToString());
        }
    }


Hope this helps,

Regards

Tags: ,

Comments are closed