[英]Get All Web Controls of a Specific Type on a Page
我一直在思考如何在頁面上獲取所有控件,然后在相關問題中對它們執行任務:
我需要可以掃描頁面的代碼,獲取所有DropDownList控件並將它們返回到列表中。
我目前不得不編輯每個單獨的控件,我寧願能夠動態循環每個控件來執行我的任務。
檢查我以前的SO答案 。
基本上,我們的想法是使用以下方法包裝迭代控件集合的遞歸:
private void GetControlList<T>(ControlCollection controlCollection, List<T> resultCollection)
where T : Control
{
foreach (Control control in controlCollection)
{
//if (control.GetType() == typeof(T))
if (control is T) // This is cleaner
resultCollection.Add((T)control);
if (control.HasControls())
GetControlList(control.Controls, resultCollection);
}
}
並使用它:
List<DropDownList> allControls = new List<DropDownList>();
GetControlList<DropDownList>(Page.Controls, allControls )
foreach (var childControl in allControls )
{
// call for all controls of the page
}
[2013年11月26日編輯] :這是實現這一目標的更優雅方式。 我編寫了兩個擴展方法,可以在兩個方向上遍歷控制樹。 這些方法以更Linq的方式編寫,因為它產生了一個可枚舉的:
/// <summary>
/// Provide utilities methods related to <see cref="Control"/> objects
/// </summary>
public static class ControlUtilities
{
/// <summary>
/// Find the first ancestor of the selected control in the control tree
/// </summary>
/// <typeparam name="TControl">Type of the ancestor to look for</typeparam>
/// <param name="control">The control to look for its ancestors</param>
/// <returns>The first ancestor of the specified type, or null if no ancestor is found.</returns>
public static TControl FindAncestor<TControl>(this Control control) where TControl : Control
{
if (control == null) throw new ArgumentNullException("control");
Control parent = control;
do
{
parent = parent.Parent;
var candidate = parent as TControl;
if (candidate != null)
{
return candidate;
}
} while (parent != null);
return null;
}
/// <summary>
/// Finds all descendants of a certain type of the specified control.
/// </summary>
/// <typeparam name="TControl">The type of descendant controls to look for.</typeparam>
/// <param name="parent">The parent control where to look into.</param>
/// <returns>All corresponding descendants</returns>
public static IEnumerable<TControl> FindDescendants<TControl>(this Control parent) where TControl : Control
{
if (parent == null) throw new ArgumentNullException("control");
if (parent.HasControls())
{
foreach (Control childControl in parent.Controls)
{
var candidate = childControl as TControl;
if (candidate != null) yield return candidate;
foreach (var nextLevel in FindDescendants<TControl>(childControl))
{
yield return nextLevel;
}
}
}
}
}
由於this
關鍵字,這些方法是擴展方法,可以簡化代碼。
例如,要查找頁面中的所有DropDownList
,您只需調用:
var allDropDowns = this.Page.FindControl<DropDownList>();
由於使用了yield
關鍵字,並且因為Linq足夠智能來推遲執行枚舉,所以可以調用(例如):
var allDropDowns = this.Page.FindDescendants<DropDownList>();
var firstDropDownWithCustomClass = allDropDowns.First(
ddl=>ddl.CssClass == "customclass"
);
只要滿足First
方法中的謂詞,枚舉就會停止。 整個控制樹不會走路。
foreach (DropDownList dr in this.Page.Form.Controls.OfType<DropDownList>())
{
}
有這個問題,雖然我發現Steve B的答案很有用,但我想要一個擴展方法,所以重新考慮它:
public static IEnumerable<T> GetControlList<T>(this ControlCollection controlCollection) where T : Control
{
foreach (Control control in controlCollection)
{
if (control is T)
{
yield return (T)control;
}
if (control.HasControls())
{
foreach (T childControl in control.Controls.GetControlList<T>())
{
yield return childControl;
}
}
}
}
這是一個遞歸版本,它返回所請求類型的控件集合,而不是使用另一個參數:
using System.Collections.Generic;
using System.Web.UI;
// ...
public static List<T> GetControls<T>(ControlCollection Controls)
where T : Control {
List<T> results = new List<T>();
foreach (Control c in Controls) {
if (c is T) results.Add((T)c);
if (c.HasControls()) results.AddRange(GetControls<T>(c.Controls));
}
return results;
}
插入您的班級(靜態可選)。
循環瀏覽頁面上的控件並不難 - 您只需在每個控件中查看更多控件。
你可以做點什么
foreach(var control in Page)
{
if(control is DropDownList)
{
//Do whatever
}
else
{
//Call this function again to search for controls within this control
}
}
您可以使用遞歸邏輯來獲取所有控件,如下所示:
private void PopulateSelectList(Control parentCtrl, List<DropDownList> selectList)
{
foreach (Control ctrl in parentCtrl.Controls)
{
if (ctrl is DropDownList)
{
selectList.Add(((DropDownList)ctrl);
continue;
}
FindAllControls(ctrl, selectList);
}
}
如果您使用system.web.ui中的表單組件,這可以工作,但是當您從system.web.mvc中使用它們時,這不起作用,所以我想出了以下解決方法。
for (Int32 idx = 0; idx < formCollection.Count; idx += 1)
{
String Name = formCollection.Keys[idx];
String value = formCollection[idx];
if (Name.Substring(0, 3).ToLower() == "chk")
{
Response.Write(Name + " is a checkbox <br/>");
}
else if (Name.Substring(0, 5).ToLower() == "txtar")
{
Response.Write(Name + " is a text area <br/>");
}
else if (Name.Substring(0, 2).ToLower() == "rd")
{
Response.Write(Name + " is a RadioButton <br/>");
}
}
這對我有用但是我發現單選按鈕如果沒有被選中是空的,所以不會返回任何好的東西我沒有必要寫任何東西到數據庫,如果它是null
var dropDownLists = new List<DropDownList>();
foreach (var control in this.Controls)
{
if (control is DropDownList)
{
dropDownLists.Add( (DropDownList)control );
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.