Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

FindControl for Windows Forms

0.00/5 (No votes)
25 Nov 2009 1  
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.

C#
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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here