Jam*_*ght 6 linq asp.net loops
我正在循环浏览页面上的所有控件,并在某些条件下将某些类型(TextBox,CheckBox,DropDownList等)设置为Enabled = False.但是我注意到这样一个明显的页面加载循环增加.是否有可能只从Page.Controls对象获取某些类型的控件而不是循环遍历它们?可能是像LINQ这样的东西?
Bal*_*a R 14
这不能完全使用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;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
并打电话
this.GetAllControls().OfType<TextBox>().ToList().ForEach(t => t.Enabled = false);
Run Code Online (Sandbox Code Playgroud)
你可以循环遍历所有控件(嵌套的控件):
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后使用以下内容初始调用它以禁用:
SetEnableControls(this.Page, false);
Run Code Online (Sandbox Code Playgroud)