Tuesday, 12 October 2010

LINQ – fetching controls on the WinForm

Let us take a simple example, but a useful one. We start with a form, having 3 text boxes and a button. The button validates whether all the text boxes are filled up or not (a common business case).

clip_image002

We want to color background of the textboxes Red if they are empty:

clip_image004 

var textBoxes = from tBox in this.Controls.OfType<TextBox>()
      where tBox.Text.Trim() == ""
      select tBox;
foreach (TextBox tbox in textBoxes)
{
    tbox.BackColor = Color.Red;
}


We get the same result as before. Building upon this, right now we get all the text boxes but what if we want to check only the visible text boxes? We should be able to achieve it by adding ‘tBox.Visible == true’ in the LINQ query. Which brings us to the question, how do we add AND condition in LINQ? (along the way let’s add Enabled condition as well)



var textBoxes =
  from tBox in this.Controls.OfType<TextBox>()
  where tBox.Text.Trim() == "" && 
  tBox.Visible == true && 
  tBox.Enabled == true
  select tBox;


For testing the OR condition, we select not just text boxes but Combo Boxes as well.



var controls =
  from Control ctl in this.Controls
  where (ctl is TextBox || ctl is ComboBox) &&
  (ctl.Text.Trim() == "" && ctl.Visible == true && ctl.Enabled == true)
  select ctl;

No comments:

Post a Comment

Note: only a member of this blog may post a comment.