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!
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;
}
.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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With