在我的项目中,所有 .aspx 页面都继承自自定义基类页面,而该基类页面又继承自 System.Web.UI.Page。 我想在当前页面中找到控件。对于我正在使用的那个 foreach 循环
foreach(control c in page.controls)
为此,我无法将当前页面转换为 system.web.ui.page。 如何将当前页面转换到系统system.web.ui.page?
最佳答案
请注意,您正在处理一个控制树,因此您可能希望在此处进行递归。以下方法应该有所帮助(使用递归调用的 Linq):
private static IEnumerable<Control> FlattenControlTree<TFilterType>(Control control)
{
if (control is TFilterType)
{
yield return control;
}
foreach (Control contr in control.Controls.Cast<Control>().SelectMany((c) => FlattenControlTree<TFilterType>(c)))
{
if (contr is TFilterType)
{
yield return contr;
}
}
}
一天结束时,您只需调用:
var controls = FlattenControlTree<YourBaseType>(this.Page);
请注意,当涉及到大树时,这种递归不是很有效。
关于c# - 在继承自基页的页面上查找控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18651681/