想要遍历页面上存在的所有用户控件并获取其ID。我该怎么做?
答案 0 :(得分:11)
要获取每个用户控件,您必须测试控件的类型:
编辑:我修改了我的示例,以递归方式遍历所有控件:
方式强>
public void GetUserControls(ControlCollection controls)
{
foreach (Control ctl in controls)
{
if (ctl is UserControl)
{
// Do whatever.
}
if (ctl.Controls.Count > 0)
GetUserControls(ctl.Controls);
}
}
<强>调用强>
GetUserControls(Page.Controls);
答案 1 :(得分:3)
这应该有效:
var listOfUserControls = GetUserControls(Page);
...
public List<UserControl> GetUserControls(Control ctrl)
{
var uCtrls = new List<UserControl>();
foreach (Control child in ctrl.Controls) {
if (child is UserControl) uCtrls.Add((UserControl)child);
uCtrls.AddRange(GetUserControls(child);
}
return uCtrls;
}
答案 2 :(得分:2)
foreach(Control control: Page.Controls)
{
//do something with control object
}
答案 3 :(得分:2)
我创建了一个扩展方法来实现这一点,它与LINQ非常合作。
<Extension()>
Public Function DecendentControls(ParentControl As Control) As Control()
Dim controls As New List(Of Control)
For Each myControl As Control In ParentControl.Controls
controls.Add(myControl)
controls.AddRange(myControl.DecendentControls)
Next
Return controls.ToArray
End Function
然后使用LINQ,您可以执行以下操作,将页面上的所有复选框设置为取消选中:
For Each myControl As CheckBox In pnlMain.DecendentControls.Where(Function(x) TypeOf x Is CheckBox)
myControl.Checked = False
Next