I have been pondering how I can get all controls on a page and then perform a task on them in this related question:
How to Search Through a C# DropDownList Programmatically
I need code that can scan the page, get all DropDownList Controls and return them in a list.
I’m currently having to edit each individual control, I would rather be able to dynamically loop over each control to preform my task.
Check my previous SO answer.
Basically, the idea is to wrap the recursion of iterating through the controls collection using :
and to use it :
[Edited 11/26/2013]: here is a more elegant way to reach this goal. I wrote two extensions methods that can walk the control tree in both directions. The methods are written in a more Linq way as it produces an enumerable:
Thanks to the
thiskeyword, these methods are extensions methods and can simplify the code.For example, to find all
DropDownListin the page, you can simply call:Because of the use of the
yieldkeyword, and because Linq is smart enough to defer execution of the enumeration, you can call (for example):The enumeration will stop as soon as the predicate in the
Firstmethod is satisfied. The whole control tree won’t be walked.