Home > Programming, Visual Basic > LINQ on Form’s Controls

LINQ on Form’s Controls

When loading a particular form in a project of mine I needed to shift the location of most of my controls to “hide” an unused textbox based on a boolean. I was going to simply loop through each control and ignore the shift in location if the name values were the two controls that were fixed but I thought about how LINQ to Objects could help. While this is simple and probably overkill the potential is awesome.

1
2
3
4
5
6
Dim res = From ctrl In Controls.OfType(Of Control)() _
             Where ctrl.Name <> "txtAddress" AndAlso ctrl.Name <> "lblAddress"
 
For Each ctrl As Control In res
     ctrl.Top -= val
Next

Admittedly this is pretty boring. But say you wanted to change the background color of all textboxes on a form that contain a string greater than 255 and are not read only.

1
2
3
4
5
6
Dim res = From ctrl In Controls.OfType(Of TextBox)() _
             Where ctrl.Text.Length > 255 And ctrl.ReadOnly = False
 
For Each ctrl As Control In res
     ctrl.BackgroundColor = Colors.Red
Next

Very quickly you can see how LINQ can be a convenient tool for all sorts of problems. And ends up being very, very readable as well.

  1. No comments yet.
  1. No trackbacks yet.