Search for a control in TabControl

Everything,

I am trying to find a control by name in a TabControl. However, my current method does not fall to the children of the control. What is the best way to do this.

Control control = m_TabControlBasicItems.Controls[controlName]; 

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

Thanks!

+4
source share
6 answers

You need to go through all the controls to find the right one.

Here is a great example for you. You should be able to copy and paste and invoke it without mods.

Insert 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; } 
+3
source

.NET does not provide a way to find nested controls. You must implement a recursive search yourself.

Here is 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; } } 
+3
source

try iterating over all containers in the tab bar:

 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 } 
+2
source

try the following:

 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; } 
+1
source

mmm, did you consider interfaces instead of names? change the type of control to a class that derives from the current type of control and implements an interface that identifies the desired control. You can then cycle through the children of the tab controls to look for the controls that implemented the interface. Thus, you can change the name of the control without breaking the code and get a compile-time check (there is no typo error in the name).

0
source

See MSDN for ...

System.Web.UI.Control.FindControl (row identifier);

Recursively search for a child control of a control identifier control.

Works great for me.

-one
source

All Articles