2009-10-29 75 views
4

全部,在TabControl中查找控件

我试图在TabControl中按名称查找控件。但是,我现在的方法并没有降到控制的孩子身上。什么是最好的办法做到这一点

Control control = m_TabControlBasicItems.Controls[controlName]; 

控制总是空,因为它是两个(或三个)以下的层次。 TabPage,GroupBox,有时Panel在收音机按键的情况下

谢谢!

+0

谢谢大家快速解答! – Billy 2009-10-29 02:33:24

回答

3

您需要通过所有的控制改乘找到合适的人。

Here是一个很好的例子。你应该能够复制并粘贴并将其称为不带mod。

粘贴代码片段的情况下,链接死亡

/// <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; 
} 
+0

btw不得不将if(container.ID == name)改为if(container.Name == name) – Billy 2009-10-29 02:34:19

+0

可能是因为.ID是用于ASP.NET Web Control标识;而.Name是Windows窗体控件标识。两套不同的控件。 – 2009-10-29 02:40:07

+0

死链接 - 请更改? – Ash 2013-06-07 11:48:10

2

尝试循环遍历标签面板所有的容器:

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 
} 
3

.NET不公开的方式来寻找嵌套控件。你必须自己实现一个递归搜索。

下面是一个例子:

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; 
     } 
    } 
0

嗯,你有没有考虑接口而不是名称?将控件的类型更改为从当前类型的控件派生出来的类,并实现一个用于标识所需控件的接口。然后,您可以递归地循环访问该选项卡的子控件,以查找实现该接口的控件。通过这种方式,您可以在不破坏代码的情况下更改控件的名称,并获得编译时间检查(无错字错误)。

1

试试这个:

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

查看MSDN了解...

System.Web.UI.Control.FindControl(串号);

通过控件ID进行递归搜索控件的子控件。

适用于我。