65.9K
CodeProject is changing. Read more.
Home

Disable Child Controls Recursively

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (5 votes)

Oct 28, 2010

CPOL
viewsIcon

21530

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)
            {
            }
    }