Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Disable Child Controls Recursively

4.00/5 (5 votes)
31 Oct 2010CPOL 21.5K  

Trying to disable a div on a certain event, but for a div there is no such a property named Enabled, and if we use attribute["disabled"] the controls inside are not disabled, just have a gray color.. !! Same when using a UserControl that have child controls


The child controls will not be disabled..


So, I wrote a method that uses recursion to go down deep and disable each child Control in any given parent Control.


The method takes two parameters



  • 1st the main control
  • 2nd status flage

// to enable\disable the control & its child controls
public void ControlStatus(Control control, bool isDisable)
    {
        foreach (Control c in control.Controls)
            try
            {
                if (c.HasControls())
                    ControlStatus(c, isDisable);
                else
                {
                    if (isDisable)
                    {
                        if (c is WebControl)
                            ((WebControl)c).Enabled = false;
                    }
                    else
                    {
                        if (c is WebControl)
                            ((WebControl)c).Enabled = true;
                    }
                }
            }
            catch (Exception)
            {
            }
    }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)