Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# ControlCollection Extension GetAllTextboxes

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#

like image 398
Melursus Avatar asked May 01 '26 03:05

Melursus


2 Answers

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>();
}
like image 86
Rex M Avatar answered May 03 '26 20:05

Rex M


You want OfType():

public static IEnumerable<TextBox> TextBoxes(this ControlCollection controlCollection)
{
    return controlCollection.OfType<TextBox>();
}
like image 22
dahlbyk Avatar answered May 03 '26 18:05

dahlbyk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!