Spontaneous Publicity
blogs are the new phone book

How to Traverse the Control Tree in Asp.Net with C# 2.0

September 20, 2006 11:00 by Luke

I couldn't find any easy way to traverse the entire asp .net control tree using the framework classes, so I decided to write my own implementation.  In the end, I wanted to be able to traverse all of the controls and get all which are of a certain type.  First, the method which traverses the tree:

public static void RecurseControls(ControlCollection controls, FindControlDelegate callback) { foreach (Control c in controls) { callback(c); if (c.Controls.Count > 0) { RecurseControls(c.Controls, callback); } } }

This basically recurses through the control tree and calls a given delegate for each control found.  Here is the delegate:

public delegate void FindControlDelegate(Control control);

To top it all off, here is the method I wrote to find all of the controls of a given type on a page:

public static List<T> FindAllControls<T>(Page page) where T : Control { List<T> controls = new List<T>(); RecurseControls(page.Controls, delegate(Control c) { if(c is T) controls.Add(c as T); }); return controls; }

I am usually not one to use cryptic programming techniques such as inline delegates, but in this case it just made sense.  Otherwise, I would have had to somehow share the object containing the list of found controls between two different methods.


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:
Categories: .Net | C# | Development
Actions: E-mail | Permalink | Comments (1) | Comment RSSRSS comment feed

Related posts

Comments

September 10. 2008 06:31

Dilli

Hey Good work

Dilli

Add comment


(Will show your Gravatar icon)  

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

November 21. 2008 22:32