Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net / C#, Loop through certain controls on a page?

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?

like image 337
James P. Wright Avatar asked Feb 25 '11 21:02

James P. Wright


2 Answers

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);
like image 198
Bala R Avatar answered Oct 15 '22 13:10

Bala R


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);  
like image 5
Kelsey Avatar answered Oct 15 '22 13:10

Kelsey