Forms : Enabled/Disable all controls in a container (panel)

user3736648 picture user3736648 · Apr 13, 2015 · Viewed 31.5k times · Source

I am coding a C# Forms application and would like to know how to enable/disable all controls container within a panel.

Here is my code:

private void EnabledPanelContents(Panel panel, bool enabled)
{
    foreach (var item in panel.Controls)
    {
        item.enabled = enabled;
    }
}

There is no enabled property in the panel.Controls collection.

How can I enable/disable all controls container within a panel.

Thanks in advance.

Answer

Mairaj Ahmad picture Mairaj Ahmad · Apr 13, 2015

You are getting controls as var and iterating on them and var doesn't contain any property Enabled. You need to loop through controls and get every control as Control. Try this

private void EnabledPanelContents(Panel panel, bool enabled)
{
    foreach (Control ctrl in panel.Controls)
    {
        ctrl.Enabled = enabled;
    }            
} 

Enabled can be true or false.