Free Information Technology Magazines and eBooks

Tuesday, May 26, 2009

Enable/Disable Multiple Textboxes on Form using LINQ

Previously, I discussed about How to disable/enable multiple textboxes using VB.NET. On this blog post, I will show you how to do the same function using Language Integrated Query or LINQ. Although there is no performance benefit by using LINQ, in my opinion it is more readable and organize. You can also create complex queries in a simple manner which were previously difficult.


To clear enable/disable textboxes on form using LINQ, see the following code:

In VB.NET

Private Sub EnableTextboxes(ByVal blnenable As Boolean)
'Retrieve all textbox controls using LINQ
Dim myChildTextBoxes = From myChildControl As Control In Me.Controls _
Where TypeOf myChildControl Is TextBox _
Select myChildControl
'Loop through my TextBoxes.
For Each myChildTextBox As TextBox In myChildTextBoxes
'Clear the TextBox.
myChildTextBox.Enable = blnenable
Next

End Sub


C#

private void enabletextbox(bool blnenable)
{
//Retrieve all textbox controls using LINQ
var myChildTextBoxes = from Control myChildControl in this.Controls
where myChildControl is TextBox
select myChildControl;

// Loop through my TextBoxes.
foreach (TextBox myChildTextBox in myChildTextBoxes)
{
// enable the TextBox.
myChildTextBox.Enabled = blnenable;
}
}

For more LINQ coding tips, subscribe now

1 comments:

Caio Proiete said...

Hi,

Another way to do the same thing(easier IMHO) would be to just use a few chaining methods and a lambda expression

// Loop through the form TextBoxes and enable or disable each one
this.Controls
.OfType<TextBox>()
.ToList()
.ForEach(t => t.Enabled = blnenable);