【问题标题】:How can I loop thru all controls (including ToolStripItems) C#如何循环遍历所有控件(包括 ToolStripItems)C#
【发布时间】:2010-12-22 04:55:18
【问题描述】:

我需要保存和恢复表单上特定控件的设置。

我遍历所有控件并返回名称与我想要的匹配的那个,如下所示:

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),但 name 属性没有值,因此代码与它不匹配。

关于如何使用这些控件的任何建议?

干杯, 穆雷

【问题讨论】:

  • 我认为toolStrip.Controls.Count != toolStrip.Items.Count。您必须专门检查控件是否为 ToolStrip,然后检查其 Items[]。

标签: c# controls


【解决方案1】:

感谢你们的帮助。

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

【讨论】:

    【解决方案2】:

    试试这个:

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

    【讨论】:

      猜你喜欢
      • 2019-01-17
      • 2015-06-11
      • 1970-01-01
      • 2012-02-10
      • 1970-01-01
      • 1970-01-01
      • 2019-01-26
      • 1970-01-01
      • 2017-03-09
      相关资源
      最近更新 更多