Nov 25 2009

FindControl for Windows Forms

Category: MobileJoel Ivory Johnson @ 12:22

Some one asked a question in the Windows Mobile programming forums about dynamically finding a control at runtime.  When I saw the question the first solution that came to mind was Control.FindControl.  Before I suggested using that method I searched for the MSDN documentation on it and found that it only existed in ASP.Net.  It's missing from Windows Forms all together. So I put together a quick implementation of the function.

Control FindControl(string target )
{
    return FindControl(this, target);
}

static Control FindControl(Control root, string target)
{
    if(root.Name.Equals(target))
        return root;
    for(var i=0;i<root.Controls.Count;++i)
    {
        if (root.Controls[i].Name.Equals(target))
            return root.Controls[i];
    }
    for(var i=0;i<root.Controls.Count;++i)
    {
        Control result;
       for(var k=0;k<root.Controls[i].Controls.Count;++k)
       {
           result = FindControl(root.Controls[i].Controls[k], target);
           if(result!=null)
               return result;
       }
    }
    return null;
}

To use the function just define it on the root of the form in which you need the functionality.  If you cannot define it on a root form the then you can use the static version of it passing to the method a reference to a container of the control hierarchy in which you wish to search.  The function will recursively search deeper and deeper into the control hierarchy until it finds a UI object with the name specified or it will return null if no such object can be found.

Tags: ,