如何循环所有控件(包括ToolStripItems)C#

问题描述:

我需要保存和恢复窗体上特定控件的设置。如何循环所有控件(包括ToolStripItems)C#

我环通所有的控制和返回名称相匹配的我想要的,就像这样:

private static Control GetControlByName(string name, Control.ControlCollection Controls) 
{ 
    Control thisControl = null; 
    foreach (Control c in Controls) 
    { 
    if (c.Name == name) 
    { 
     thisControl = c; 
     break; 
    } 
    if (c.Controls.Count > 0) 
    { 
     thisControl = GetControlByName(name, c.Controls); 
     if (thisControl != null) 
     { 
     break; 
     } 
    } 
    } 
    return thisControl; 
} 

从这个我能确定,应该是控制的类型,因此,物业/已存储。

这很适用,除非控件是已添加到工具条的ToolStrip系列之一。例如

this.toolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { 
     this.lblUsername, // ToolStripLabel 
     this.toolStripSeparator1, 
     this.cbxCompany}); // ToolStripComboBox 

在这种情况下,我可以看到在调试的时候我很感兴趣(cbxCompany)的控制,但名称属性没有值,使代码不匹配它。

关于如何获得这些控件的任何建议?

欢呼声中,穆雷

+0

我认为`toolStrip.Controls.Count!= toolStrip.Items.Count`。您必须特别检查控件是否为ToolStrip,然后检查其Items []。 – pinichi 2010-12-22 05:05:00

感谢您的帮助球员。

Pinichi设置我在正确的轨道上,我被检查toolStrip.Controls - 本来应该toolStrip.Items

低于现在的代码工作完美的我:

private static Control GetControlByName(string controlName, Control.ControlCollection parent) 
{ 
    Control c = null; 
    foreach (Control ctrl in parent) 
    { 
    if (ctrl.Name.Equals(controlName)) 
    { 
     c = ctrl; 
     return c; 
    } 

    if (ctrl.GetType() == typeof(ToolStrip)) 
    { 
     foreach (ToolStripItem item in ((ToolStrip)ctrl).Items) 
     { 
     if (item.Name.Equals(controlName)) 
     { 
      switch (item.GetType().Name) 
      { 
      case "ToolStripComboBox": 
       c = ((ToolStripComboBox)item).Control; 
       break; 
      case "ToolStripTextBox": 
       c = ((ToolStripTextBox)item).Control; 
       break; 
      } 
      if (c != null) 
      { 
      break; 
      } 
     } 
     } 
    } 
    if (c == null) 
     c = GetControlByName(controlName, ctrl.Controls); 
    else 
     break; 
    } 
    return c; 
} 

试试这个:

//for toolstrip 
      if (ctrl is ToolStrip) 
      { 
       ToolStrip ts = ctrl as ToolStrip; 
       foreach (ToolStripItem it in ts.Items) 
       { 
        if (it is ToolStrienter code herepSeparator) 
        { 
         //------------------------- 
        } 
        else 
        { 
         //do something 
        } 

       } 
      }//---------------