65.9K
CodeProject is changing. Read more.
Home

FindControl for Windows Forms

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (6 votes)

Nov 25, 2009

CPOL
viewsIcon

52563

A quick implementation of FindControl for Windows Forms.

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 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, 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.