tags:

views:

217

answers:

5

All,

I am attempting to find a control by name within a TabControl. However my current method does not drop down to the children of the control. What is the best way to do this

Control control = m_TabControlBasicItems.Controls[controlName];

control is alway null because it is two (or three) levels below. TabPage, GroupBox, and sometimes Panel in the case of radioButtons

Thank You!

+2  A: 

try looping over all the containers in tab-panel:

foreach(var c in tab_panel.Controls)
{
   if(c is your control)
     return c;

   if(c is a container)
     loop through all controls in c;//recursion
}
TheVillageIdiot
+3  A: 

.NET does not expose a way to search for nested controls. You have to implement a recursive search by yourself.

Here's an example:

public class MyUtility
    {
        public static Control FindControl(string id, ControlCollection col)
        {
            foreach (Control c in col)
            {
                Control child = FindControlRecursive(c, id);
                if (child != null)
                    return child;
            }
            return null;
        }

        private static Control FindControlRecursive(Control root, string id)
        {
            if (root.ID != null && root.ID == id)
                return root;

            foreach (Control c in root.Controls)
            {
                Control rc = FindControlRecursive(c, id);
                if (rc != null)
                    return rc;
            }
            return null;
        }
    }
Ciwee
+1  A: 

You need to recurse through all of the controls to find the right one.

Here is a perfect example for you. You should be able to copy and paste and call it w/o mods.

Paul Sasik
btw had to change if (container.ID == name) to if (container.Name == name)
Billy
Likely because .ID is for ASP.NET Web Control identification; whereas .Name is for Windows Forms Control identification. Two different sets of controls.
John K
A: 

mmm, did you consider interfaces instead of names? change the control's type to a class that derives from the current type of the control and implements an interface that identify the control you wanted. Then you can loop though the child controls of the tab recursively to look for controls that implemented the interface. In this way you can change the control's name without breaking the code, and get compile time check (no typo mistake in name).

Sheng Jiang 蒋晟
+1  A: 

try this:

Control FindControl(Control root, string controlName)
{
    foreach (Control c in root.Controls)
    {
        if (c.Controls.Count > 0)
            return FindControl(c);
        else if (c.Name == controlName)
            return c;            
    }
    return null;
}
Michael Buen