Finding all controls of specified type on a form

J

Joe S.

I need to find all instances of a specific type of control on a Windows
Form -- for example all DataGrids. The code I came up with is this:

foreach(Control ctrl in this.Controls)
{
if(ctrl.GetType() == Type.GetType("System.Windows.Forms.DataGrid"))
Console.WriteLine(((DataGrid)ctrl).Name);
}

This code has two problems. Something's wrong with the type checking,
because it doesn't find any DataGrids on a form.

Even if it did work, the second problem is that this would find only
DataGrids put directly on the form (in the Form.Controls collection), but a
Grid can also be in the ControlCollection of a GroupBox or some other
container. How to loop through all controls in a form regardless of their
parent control?

Best regards,
Joe
 
A

Andrew Smith \(Infragistics\)

You need to write a recursive routine to find all of the controls on the
form; its pretty easy since every control has Controls property returning
its child controls. With regards to the code you listed, your code for
GetType is not going to return a type so its going to fail - it would also
fail if you had a control that derived from DataGrid since you're
specifically looking for that type. Its better to use "is" to determine if
something "is" a particular type.

e.g.
IterateControls(this.Controls);

public static void IterateControls(Control.ControlCollection controls)
{
foreach(Control child in controls)
{
if (child is DataGrid)
Console.WriteLine(child.Name);

if (child.HasChildren)
IterateControls(child.Controls);
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top