2010-05-14 90 views
0

我想枚举通过页面的所有控件,但我可以找到的是thePage.FindControl(string)和.Controls属性不具有我在页面上的控件。任何人都知道如何枚举通过web窗体页面的所有控件,这有可能吗?

回答

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

Controls属性只包含当前控件的直接子项。如果要遍历页面上的所有控件,则必须遍历页面的子元素,然后递归遍历子元素,然后再遍历子元素的孩子等等。递归方法是实现这一点最直接的方法。