C# Query Windows Forms (Controls.OfType)

Use query expressions on Windows Forms controls. Invoke the OfType method.

Query controls. Windows Forms controls can be searched. This is often done with a foreach-loop. Another option uses LINQ—a query expression can locate the control. There is a performance difference with these approaches. The foreach-loop is faster.OfType

Methods. This example shows 4 ways of finding the first TextBox control that has focus in a Windows Forms program. The methods use LINQ expressions with the query syntax, extension methods, and the foreach-loop.TextBoxLINQ

Example 1: First we see the LINQ code version. It uses the var implicit type keyword for simpler syntax.


Example 2: Here is a different version of our method. LINQ allows you to write database-like queries on various objects, including Windows Form controls.

Example 3: Here we look at a method that doesn't use LINQ. It tests every control for whether it is a TextBox and has focus. This is imperative code.

Windows Forms and OfType method: C# /// <summary> /// Use a LINQ query to find the first focused text box on a windows form. /// </summary> public TextBox TextBoxFocusedFirst1() { var res = from box in this.Controls.OfType<TextBox>() where box.Focused == true select box; return res.First(); } Using foreach-loop: C# /// <summary> /// Use a combination of methods to find the right TextBox. /// </summary> public TextBox TextBoxFocusedFirst2() { foreach (TextBox t in mainForm.Controls.OfType<TextBox>()) { if (t.Focused == true) { return t; } } } Using is-operator: C# /// <summary> /// Classic code to search form collections. /// </summary> public TextBox TextBoxFocusedFirst3() { foreach (Control con in mainForm.Controls) { if (con is TextBox && con.Focused == true) { return con as TextBox; } } } Using as-operator: C# /// <summary> /// Classic code to search form collections. /// </summary> public TextBox TextBoxFocusedFirstX() { foreach (Control con in mainForm.Controls) { if (con.Focused == true) { TextBox textBox = con as TextBox; if (textBox != null) { return textBox; } } } } Output Foreach: 780 ms LINQ version: 889 ms

Notes, cast. I did a bit more tinkering and I found an even better version. This version will avoid one cast and performs about ten percent better than the second version. Note that it uses no LINQ.

Summary. We saw ways to use LINQ on Windows Forms controls. Avoiding the LINQ syntax and OfType is faster. So, my recommendation is this: don't use LINQ just because it is there. But if it makes your life easier, it doesn't have a large penalty.
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to