Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Find a Parent Control Recursively

4.67/5 (2 votes)
24 Sep 2010CPOL 19.5K  
Useful function, but I don't see any need for an recursion here. I'd solve it like this:private static Control FindControlParent(Control control, Type type) { Control ctrlParent = control; while((ctrlParent = ctrlParent.Parent) != null) { ...
Useful function, but I don't see any need for an recursion here. I'd solve it like this:

C#
private static Control FindControlParent(Control control, Type type)
        {
            Control ctrlParent = control;
            while((ctrlParent = ctrlParent.Parent) != null)
            {
                if(ctrlParent.GetType() == type)
                {
                    return ctrlParent;
                }
            }
            return null;
        }


and use it like this:

TabControl tc = FindControlParent(control, typeof(TabControl)) as TabControl;

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)