Reputation: 9131
I am currently looping through all the controls on my page and setting certain types (TextBox, CheckBox, DropDownList, etc.) to Enabled=False under certain conditions. However I notice an obvious page load increase looping like this. Is it possible to only get certain types of controls from the Page.Controls object rather than Loop through them all? Possibly with something like LINQ?
Upvotes: 6
Views: 9864
Reputation: 41
I like the solution in this link LINQ equivalent of foreach for IEnumerable<T>
Worked quite well for me!
You can do the iteration of controls using a linq query like
(from ctrls in ModifyMode.Controls.OfType<BaseUserControl>()
select ctrls).ForEach(ctrl => ctrl.Reset());
Here BaseUserControl is a base class which all my controls use, you could very well use Control itself here, and the extension method allows you to club iteration and execution.
Upvotes: 0
Reputation: 108937
This cannot be done entirely using LINQ but you could have an extension defined like this
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;
}
}
}
}
and call
this.GetAllControls().OfType<TextBox>().ToList().ForEach(t => t.Enabled = false);
Upvotes: 14
Reputation: 47726
You could loop through all the control (an nested ones):
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);
}
}
}
Then just call it initally with the following to disable:
SetEnableControls(this.Page, false);
Upvotes: 5