LINQ to Objects: VB TextBox Edition

Here's an example of looping through Form textboxes using VB LINQ and disabling the boxes:

Dim formBoxes = From formControls In Form.Controls _
Where formControls.GetType() Is GetType(TextBox) _
Select formControls

 

For Each oBox In formBoxes

CType(oBox, TextBox).Enabled = False

Next

Print | posted on Friday, June 20, 2008 10:34 AM

Feedback

# re: LINQ to Objects: VB TextBox Edition

left by Jim Wooley at 6/20/2008 11:51 AM Gravatar
While that is nice, you can eliminate the additional cast by slightly changing your query using "OfType" in the from clause rather than "Is" in the Where clause:

Dim formBoxes = From formControls In Form.Controls.OfType(Of TextBox)
Select formControls

For Each oBox In formBoxes
oBox.Enabled = False
Next

Notice we don't need to do the additional cast in the iteration because we already took care of strongly typing the results in the OfType method. If you compare the two, your version infers the formBoxes type as IEnumberable(Of Control) where mine infers it as IEnumerable(Of TextBox).

# re: LINQ to Objects: VB TextBox Edition

left by Matt at 6/20/2008 12:52 PM Gravatar
Thanks. I was thinking of doing that but I'm just learning LINQ and I was trying to apply the cast to the oBox definition in the For Each line but it's great to know I can do that in the LINQ statement.
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: