c# - 如何遍历所有控件(包括 ToolStripItems)C#

标签 c# controls

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

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

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

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

干杯, 默里

最佳答案

感谢您的帮助。

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

关于c# - 如何遍历所有控件(包括 ToolStripItems)C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4506275/

相关文章:

c# 项目找不到 c++ .dll?

java - 隐藏布局中的所有控件

.net - 如何找出.NET Windows窗体中关注焦点的控件?

C# 套接字模型 View 控件

c# - 如何创建具有顶部 float 控件和自动调整大小的布局?

c# - 在 C# 中使用 F# 选项类型

c# - 为什么将设计模式分为三部分?

Excel VBA : Frame doesn't appear in front of ListBox

c# - 使用EF CodeFirst,如何在创建对象时指定ID?

c# - 如何用C#检查asp.net中是否存在域名?