2011-08-18 48 views

回答

1

如果你不需要担心嵌套控件,在这种情况下你需要递归,像下面的东西应该工作。

foreach(DropDownList list in Controls.OfType<DropDownList>()) 
{ 
    //TODO: Something with list 
} 

如果需要递归你可以做类似下面的方法..

public static IEnumerable<Control> GetAllControls(Control parent) 
{ 
    if(null == parent) return null; 

    return new Control[] { parent }.Union(parent.Controls.OfType<Control>().SelectMany(child => GetAllControls(child)); 
} 

然后修改你的循环......

foreach(DropDownList list in GetAllControls(this).OfType<DropDownList>()) 
{ 
    //TODO: Something with list 
} 
1

没有神奇的所有控件容器。你将不得不递归遍历你的控制树并找到所有的下拉菜单。

public void DoSomethingForAllControlsOf<T>(Control thisControl, Action<T> method) 
    where T: class 
{ 
    if(thisControl.Controls == null) 
     return; 

    foreach(var control in thisControl.Controls) 
    { 
     if(control is T) 
      method(control as T); 

     DoSomethingForAllControlsOf<T>(control, method); 
    } 
} 

这应该递归走在控件树和调用方法上的T类型实例的所有元素:

DoSomethingForAllControlsOf<DropDownList>(this, someFunction); 
0

你不能在运行foreach循环,因为虽然你有大量的DropDownLists,它们不是可迭代集合的一部分。但是,您可以将每个DropDownList存储到一个数组中,并遍历该数组。

1
foreach (var dropDownList in Page.Controls.OfType<DropDownList>()) 
{ 

} 
0

要获取所有下拉控件,您可能需要循环递归。您可以使用此功能来做到这一点:

public Control DisableDropDowns(Control root) 
{    
    foreach (Control ctrl in root.Controls) 
    { 
     if (ctrl is DropDownList) 
      ((DropDownList)ctrl).Enabled = false; 
     DisableDropDowns(ctrl); 
    } 
} 
0

的LINQ方式:

首先,你需要一个扩展的方法来抓住你感兴趣的所有类型的控件:

//Recursively get all the formControls 
public static IEnumerable<Control> GetAllControls(this Control parent) 
{ 
    foreach (Control control in parent.Controls) 
    { 
     yield return control; 
     foreach (Control descendant in control.GetAllControls()) 
     { 
      yield return descendant; 
     } 
    } 
}` 

然后你可以迭代你想要的:

var formCtls = this.GetAllControls().OfType<DropDownList>();` 

foreach(DropDownList ddl in formCtls){ 
    //do what you gotta do ;) 
}