我目前正在遍历页面上的所有控件,并在某些条件下将特定类型(TextBox、CheckBox、DropDownList等)设置为Enabled=False。 然而,我注意到像这样循环会导致页面加载明显增加。是否可能仅从Page.Controls对象中获取某些类型的控件,而不是遍历它们?可能使用类似于LINQ的东西吗?
这不能完全使用LINQ来完成,但您可以定义一个扩展方法来实现,如下所示:
static class ControlExtension
{
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;
}
}
}
}
并调用
this.GetAllControls().OfType<TextBox>().ToList().ForEach(t => t.Enabled = false);
private void SetEnableControls(Control page, bool enable)
{
foreach (Control ctrl in page.Controls)
{
// not sure exactly which controls you want to affect so just doing TextBox
// in this example. You could just try testing for 'WebControl' which has
// the Enabled property.
if (ctrl is TextBox)
{
((TextBox)(ctrl)).Enabled = enable;
}
// You could do this in an else but incase you want to affect controls
// like Panels, you could check every control for nested controls
if (ctrl.Controls.Count > 0)
{
// Use recursion to find all nested controls
SetEnableControls(ctrl, enable);
}
}
}
然后,只需使用以下内容进行初始调用以禁用:
SetEnableControls(this.Page, false);
getControls(Type type)
可以返回给定类型的所有控件,而且linq也会进行循环。 - Tim Schmelter我喜欢这个链接中的解决方案 LINQ equivalent of foreach for IEnumerable<T>
对我来说效果很不错!
你可以使用类似于linq查询的方式来迭代控件
(from ctrls in ModifyMode.Controls.OfType<BaseUserControl>()
select ctrls).ForEach(ctrl => ctrl.Reset());
这里的BaseUserControl是我所有控件使用的基类,你也可以在这里直接使用Control本身,而扩展方法允许你将迭代和执行组合在一起。
Page.Controls
本身不应该对性能造成太大的影响。 - jevakallio