2

How could I get only the texboxes in a ControlCollection ?

I try :

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 cast object of type 'WhereEnumerableIterator`1[System.Web.UI.Control]' to type 'System.Collections.Generic.IEnumerable`1[System.Web.UI.WebControls.TextBox]'.

I Use Asp.Net 3.5 with C#

Rex M
  • 142,167
  • 33
  • 283
  • 313
Melursus
  • 10,328
  • 19
  • 69
  • 103

4 Answers4

12

You don't actually need a new extension method - there's already one for you that will get this:

controlCollection.OfType<TextBox>();

The OfType method returns a sequence (IEnumerable<T>) subset of the sequence provided. If the type isn't convertible, it's left out. Unlike most of the LINQ extension methods, OfType is available on sequences that aren't strongly-typed:

This method is one of the few standard query operator methods that can be applied to a collection that has a non-parameterized type, such as an ArrayList. This is because OfType<(Of <(TResult>)>) extends the type IEnumerable.

Or if you do want to wrap it in an extension method, it's of course quite simple:

public static IEnumerable<TextBox> TextBoxes(this ControlCollection controls)
{
    return controls.OfType<TextBox>();
}
Rex M
  • 142,167
  • 33
  • 283
  • 313
1

You want OfType():

public static IEnumerable<TextBox> TextBoxes(this ControlCollection controlCollection)
{
    return controlCollection.OfType<TextBox>();
}
dahlbyk
  • 75,175
  • 8
  • 100
  • 122
1

Here is a recursive extension method to get the Control objects that descend from the specified type, including those that are 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 instead of ASP.NET, substitute Control.ControlCollection for ControlCollection.)

Jason Kresowaty
  • 16,105
  • 9
  • 57
  • 84
  • 1
    Or you could use OfType() with the non-recursive GetDescendantControls() method defined here: http://solutionizing.net/2009/06/23/refactoring-with-linq-iterators-finddescendantcontrol-and-getdescendantcontrols/ – dahlbyk Oct 11 '09 at 02:21
1
foreach (TextBox tBox in controls)
{

}

Example:

public static void HideControls<T>(Form pForm)
{
    foreach (T cont in pForm.Controls)
    {
        cont.Visible = false;
    }
}

HideControls<TextBox>(this);
HideControls<CheckedListBox>(this);
Blumster
  • 11
  • 1