Selectors for WebControls - Querying into the Control hierarchy on the server

December 03, 2008
I've been thinking long and hard on CSS selectors, and the thing about them is that they are really cool! They easily allow you to "query" into the DOM structure of your page and retrieve elements matching your criteria. And as a Managed Ajax library developer I must confess that until today I have envied JavaScript for this reason...

WebControl selectors for querying into Control hierarchy
Tired of code like the above?

Today WebControls and server-side Ajax got their selectors! Meet the RaSelector;

public static class Selector
{
public delegate bool FindDelegate(Control idx);

public static T SelectFirst<T>(Control from, FindDelegate del) where T : Control
{
if (del(from))
return from as T;
foreach (Control idx in from.Controls)
{
T tmpRetVal = SelectFirst<T>(idx, del);
if (tmpRetVal != null)
return tmpRetVal;
}
return null;
}

public static T SelectFirst<T>(Control from) where T : Control
{
if (from is T)
return from as T;
foreach (Control idx in from.Controls)
{
T tmpRetVal = SelectFirst<T>(idx);
if (tmpRetVal != null)
return tmpRetVal;
}
return null;
}
}

The above code allows you to "query" into the Control hierarchy on the server to retrieve items matching your criteria. Here's an example;

TextArea text = Selector.SelectFirst<TextArea>(someControl);
Couple this with a GridView or an ASP.NET Repeater and I think you can appreciate its construct...

Retrieving items inside a Repeater or GridView


When you are databinding ASP.NET Repeaters or GridViews you often end up writing a lot of really ugly "foreach code" to retrieve specific Controls inside of them. Though with the above little class all the places with this ugly code goes "out the window". Imagine a more "difficult scenario";

TextArea text = Selector.SelectFirst<TextArea>(someControl,
delegate(Control idx)
{
if (idx is RaWebControl)
return (idx as RaWebControl).CssClass == "colorful";
return false;
});

The above code will return the first TextArea with "colorful" as its CssClass. And it will recursively traverse the Control hierarchy for you until it does. Pretty cool if you've got complex DataBinding scenarios where you would otherwise need to traverse with "15 levels of nested foreach blocks"...

Now currently this is just a teaser. We will extend it with all sort of methods, including ControlCollection helpers which can modify more then one control at the time. But already it has saved us for more then 60 lines of code in Stacked :)

Have fun, I did - and as always; All code in my BLOGS are MIT.


.t

<< Previous - First Release of Stacked - an Open Source version of StackOverflow.com
Why is Ra-Ajax so slow...? - Next >>