views:

231

answers:

2

Hi, I'm trying to use the page control's collection with LINQ. Whereas this works:

dim l = Me.Controls.OfType(Of TextBox).AsQueryable()

the following return an ArgumentExceptionError:

dim l = Me.Controls.AsQueryable()

I need all the controls. Any help? Thanks

+1  A: 

Have you tried:

Me.Controls.Cast(Of Control)

Out of interest, why do you need it as an IQueryable? Isn't IEnumerable<T> enough for you? (That's the result of Cast.)

The problem with just calling AsQueryable is that the control collection doesn't implement IEnumerable<T>, just IEnumerable.

Jon Skeet
+1  A: 

Also, don't forget that controls can be nested, and just asking the page for it's controls will only tell you about the direct children, but it won't tell you about the controls in those controls:

Locate the web forms controls on a page by walking the Controls Collection

This example finds only the controls contained in the Page object and the controls that are direct children of the page. It does not find text boxes that are children of a control that is in turn a child of the page. For example, if you added a Panel control to page, the Panel control would be a child of the HtmlForm control contained by the Page, and it would be found in this example. However, if you then added a TextBox control into the Panel control, the TextBox control text would not be displayed by the example, because it is not a child of the page or of a control that is a child of the page. A more practical application of walking the controls this way would be to create a recursive method that can be called to walk the Controls collection of each control as it is encountered. However, for clarity, the example below is not created as a recursive function.

Zhaph - Ben Duguid