【问题标题】:How to access find all controls and all components into form in C#?如何在 C# 中访问查找所有控件和所有组件到表单中?
【发布时间】:2011-10-07 21:24:29
【问题描述】:

我有一个窗口窗体,其中包含一些控件和一些组件(如 DataTable、XPCollection 等)。我想找到此表单中使用的所有控件名称和组件名称。

【问题讨论】:

  • 介意我问你为什么要这样做吗?
  • this.Controls 会给你你想要的。迭代它,看看你得到了什么。
  • 组件没有在运行时可用的 Name 属性。

标签: c# winforms forms reflection


【解决方案1】:

你可以,

List<string> ctrlNames = new List<string>();
FIndAllCtrls(ctrlNames , this.Controls);

private void FIndAllCtrls(ctrlNames, ControlCollection ctrlColl)
{
   foreach(Control ctrl in ctrlColl)
   {
      ctrlNames.Add(ctrl.Name);
      if(ctrl.Controls.Count > 0)
         FIndAllCtrls(ctrlNames, ctrl.Controls);
   }
}

【讨论】:

  • 感谢您的回答,但此代码不返回表单组件,例如 DataTable 组件
  • DataTable组件是什么意思?
  • 要获取组件列表,请使用 this.components.Components 并对其进行迭代。
  • @Asdfg 这仅在设计时有效。在运行时this.components 为空。
【解决方案2】:
    IEnumerable<Control> EnumControls(Control top)
    {
        Queue<Control> todo = new Queue<Control>();
        todo.Enqueue(top);

        while (todo.Count > 0)
        {
            Control c = todo.Dequeue();

            yield return c;
            foreach (Control ch in c.Controls)
                todo.Enqueue(ch);
        }
    }

【讨论】:

    【解决方案3】:

    在这个节点中有解释: Find components on a windows form c# (not controls) 看来只有通过反射的方法可用。

    【讨论】:

    • 欢迎提供解决方案链接,但请确保您的答案在没有它的情况下有用:add context around the link 这样您的其他用户就会知道它是什么以及为什么会出现,然后引用最相关的您链接到的页面的一部分,以防目标页面不可用。 Answers that are little more than a link may be deleted.
    • @mrun:从另一个 stackoveflow 线程复制内容在我看来非常愚蠢。我只想在此处添加带有评论的链接,但不允许我这样做。
    • @VáclavŠvára,如果这是您的意图,那么您应该发表评论而不是回答
    • @mrum 发表评论 我必须有 50 个目前缺少的声望
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-16
    • 1970-01-01
    • 1970-01-01
    • 2011-04-09
    相关资源
    最近更新 更多