通过asp.net webforms页面控件枚举,是否可能?

时间:2010-05-14 19:47:33

标签: asp.net webforms

我正在尝试枚举页面的所有控件,但我找到的只是thePage.FindControl(string)而.Controls属性没有我在页面上的控件。任何人都知道如何枚举网页表单页面的所有控件

2 个答案:

答案 0 :(得分:2)

以下内容应为您枚举所有子控件。

IEnumerable<Control> GetAllChildControls(ControlCollection controls)
{
  foreach(Control c in controls)
  {
    yield return c;

    if(c.Controls.Count > 0)
    {
      foreach(Control control in GetAllChildControls(c.Controls))
      {
        yield return control;
      }
    }
  }
}

答案 1 :(得分:1)

Controls属性仅包含当前控件的直接子级。如果你想遍历页面上的所有控件,你将不得不遍历页面的子节点,然后递归遍历他们的孩子,然后他们的孩子的孩子等等。递归方法是实现此目的最直接的方法。