Re: Finding all controls of specified type on a form by Andrew
Andrew
Sun Aug 08 17:43:01 CDT 2004
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);
}
}
"Joe S." <dontmail@nowhere.com> wrote in message
news:Oiakp%23YfEHA.2468@TK2MSFTNGP12.phx.gbl...
> 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
>
>