Easily Select Controls Using Complex Expressions [Sizzle]
If you've used jQuery before, you know you want that kind of amazing selector functionality for .NET. The good news is that you can get that kind of complex selecting using a free code snippet called Ra.Selector. It supports finding controls by type according to a predicate (boolean expression) and also recursively finding a control by ID.
I am working on a side project, jForms.NET, a component for my current project to automagically manage the code for client validation and default values for web form controls. Basically, only need to define server-side things and it will take care of client-side things.
One of the things I do is list acceptable control types to search for and collect. My need was to search through the whole page for these controls, no matter where they were, easily letting you (the consumer) drag and drop the control on the page and be done with it.
The code, using the [modified] selector code, looks like this:
' Init member
_allControls = New List(Of Control)
' Iterate through acceptable control types
For Each T As Type In AcceptableControls
' Find controls of the type, or that inherit from the type
' to support custom subclassed controls
_allControls.AddRange(Page.FindControls(Of Control)(Function(c) _
c.GetType() Is T Or c.GetType().IsSubclassOf(T)))
Next
So it makes life a lot easier. The original code is GPL licensed in C#. I converted it to VB.NET and modified it to work (since the C# version uses the yield keyword). I am not an expert on license issues but as I understand it, that makes it a new work since I'm not using the original code.
As another example using FindFirstControl, let's say I wanted to find the first button that had text that began with the letter A:
' English: Find first control of type Button in Page where Button.Text starts with "A"
_btnControl = Page.FindFirstControl(Of Button)(Function(b) b.Text.StartsWith("A"))
I am not posting the modified code, just in case it is against the license. All I did was fix some documentation issues, change the name of the methods to match the built-in FindControl, and convert the methods into extension methods.
Note: The code above was from my project, not the new jForms component. The jForms component is written in C# and looks way cooler than that. More on that later.