Finding a control within a TabControl
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[con开发者_开发百科trolName];
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;
}
}
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
}
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;
}
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).
See MSDN for...
System.Web.UI.Control.FindControl(string id);
Does a recursive search for a child control, of a control, by control id.
Works great for me.
精彩评论