Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding a control within a TabControl

Tags:

c#

.net

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!

like image 894
Billy Avatar asked Mar 01 '23 03:03

Billy


2 Answers

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.

Pasting the code snippet in case the link dies:

/// <summary>
/// Finds a Control recursively. Note finds the first match and exists
/// </summary>
/// <param name="container">The container to search for the control passed. Remember
/// all controls (Panel, GroupBox, Form, etc are all containsers for controls
/// </param>
/// <param name="name">Name of the control to look for</param>
public Control FindControlRecursive(Control container, string name)
{
    if (container == name) return container;

    foreach (Control ctrl in container.Controls)
    {
        Control foundCtrl = FindControlRecursive(ctrl, name);

        if (foundCtrl != null) return foundCtrl;
    }

    return null;
}
like image 167
Paul Sasik Avatar answered Mar 07 '23 10:03

Paul Sasik


.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;
        }
    }
like image 23
André Pena Avatar answered Mar 07 '23 10:03

André Pena