C # ControlCollection GetAllTextboxes Extension
How can I get only the textboxes in the ControlCollection?
I'm trying to:
public static IEnumerable<TextBox> TextBoxes(this ControlCollection controlCollection)
{
return (IEnumerable<TextBox>)controlCollection.Cast<Control>().Where(c => c is TextBox);
}
But I got the following error: Unable to pass object of type "WhereEnumerableIterator`1 [System.Web.UI.Control]" for input "System.Collections.Generic.IEnumerable`1 [System.Web.UI.WebControls.TextBox]".
I am using Asp.Net 3.5 with C #
source to share
You don't really need a new extension method - there's already one for you, which will get the following:
controlCollection.OfType<TextBox>();
The OfType method returns a subset of the sequence ( IEnumerable<T>
) of the provided sequence. If the type is not convertible, it is ignored. Unlike most LINQ extension methods, it OfType
is available for sequences that are not strongly typed:
This method is one of the few standard query operator methods that can be applied to a collection that is of a non-parameterized type, such as ArrayList. This is because OfType <(Of <(TResult>)>) extends IEnumerable.
Or, if you want to wrap it in an extension method, it's of course pretty simple:
public static IEnumerable<TextBox> TextBoxes(this ControlCollection controls)
{
return controls.OfType<TextBox>();
}
source to share
Here is a recursive extension method to get objects Control
that are omitted from the specified type, including those nested in the control hierarchy.
public static class ControlCollectionExtensions
{
public static IEnumerable<T> OfTypeRecursive<T>(this ControlCollection controls) where T : Control
{
foreach (Control c in controls)
{
T ct = c as T;
if (ct != null)
yield return ct;
foreach (T cc in OfTypeRecursive<T>(c.Controls))
yield return cc;
}
}
}
(For Windows Forms, replace ASP.NET Control.ControlCollection
with ControlCollection
.)
source to share