Use the power of linq

Create a form with some controls on it and a textbox called textbox1.

then but this in the load event of the form

C#
1
2
3
4
5
6
textBox1.Clear();
            IEnumerable<Control> query = from p in this.Controls.OfType<Control>() orderby p.TabIndex select p;
            foreach (Control c in query)
            {
                textBox1.AppendText(c.TabIndex + " " + c.Name + Environment.NewLine);    
            }
textBox1.Clear();
            IEnumerable<Control> query = from p in this.Controls.OfType<Control>() orderby p.TabIndex select p;
            foreach (Control c in query)
            {
                textBox1.AppendText(c.TabIndex + " " + c.Name + Environment.NewLine);    
            }

and you probably need these usings.

C#
1
2
3
4
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

At first I couldn’t get it to work until I found this LINQ – Query Windows Forms Controls
by Sam Allen
and then the light came. I was missing the TypeOf method. This is really cool. No more reflection needed to get that control you realy need.