爲了遍歷網頁上的所有DropDownList,我必須引用什麼對象。我有一個網頁上有幾個下拉列表。我想要一段代碼,將執行以下操作:在ASP.NET WebForm中迭代所有DropDownList C#
foreach (DropDownList d in xxx)
{
someFunction(d, d.ID);
}
謝謝。
爲了遍歷網頁上的所有DropDownList,我必須引用什麼對象。我有一個網頁上有幾個下拉列表。我想要一段代碼,將執行以下操作:在ASP.NET WebForm中迭代所有DropDownList C#
foreach (DropDownList d in xxx)
{
someFunction(d, d.ID);
}
謝謝。
如果你不需要擔心嵌套控件,在這種情況下你需要遞歸,像下面的東西應該工作。
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
}
沒有神奇的所有控件容器。你將不得不遞歸遍歷你的控制樹並找到所有的下拉菜單。
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);
你不能在運行foreach循環,因爲雖然你有大量的DropDownLists,它們不是可迭代集合的一部分。但是,您可以將每個DropDownList存儲到一個數組中,並遍歷該數組。
foreach (var dropDownList in Page.Controls.OfType<DropDownList>())
{
}
要獲取所有下拉控件,您可能需要循環遞歸。您可以使用此功能來做到這一點:
public Control DisableDropDowns(Control root)
{
foreach (Control ctrl in root.Controls)
{
if (ctrl is DropDownList)
((DropDownList)ctrl).Enabled = false;
DisableDropDowns(ctrl);
}
}
的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 ;)
}