Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable ALL controls on a form?

Tags:

c#

loops

winforms

Currently I have most of my form's controls disabled at launch because you cannot use them until a file is loaded. However, once the file is loaded the controls should become enabled.

I was using bindings but I don't think they're a good solution. For one, it is unnecessary complexity. Secondly, you cannot use bindings for everything. For example, MenuStrip items cannot have their Enabled property bound to the fileLoaded property. Only the entire menu can and I don't want to disable the entire menu at launch, only certain menu operations that operate on the file.

I'm really just looking for a way to enable EVERYTHING. Most when asked that would answer with this:

foreach (Control c in Controls)
{
    c.Enabled = true;
}

However, that does not work for enabling MenuStrip items or controls within other controls (like a Panel or custom control). Therefore it would not enable scrollbars within containers.

I suppose I could use that line and manually enable everything else but I could have always just manually enabled everything. I'm looking for a way to automatically enable everything.

like image 213
John Smith Avatar asked Aug 24 '11 21:08

John Smith


People also ask

How do you put controls on a form?

Add the control by drawingSelect the control by clicking on it. In your form, drag-select a region. The control will be placed to fit the size of the region you selected.

How do I add controls to a form in Visual Studio?

On the left side of the Visual Studio IDE, select the Toolbox tab. If you don't see it, select View > Toolbox from the menu bar or Ctrl+Alt+X. In the toolbox, expand Common Controls. Double-click PictureBox to add a PictureBox control to your form.


2 Answers

Recursion

private void enableControls(Control.ControlCollection Controls)
{
    foreach (Control c in Controls)
    {
        c.Enabled = true;
        if (c is MenuStrip)
        {
           foreach(var item in ((MenuStrip)c).Items)
           { 
              item.Enabled = true;
           }
        }
        if (c.ControlCollection.Count > 0)
            enableControls(c.Controls);

    }
}

Edit

Should have been checking the control Collection count instead of HasControls Which is Webcontrols

like image 198
msarchet Avatar answered Sep 28 '22 08:09

msarchet


Put all controls in a panel;

panel.enable = false -> all controls in the panel will be disabled panel.enable = true -> all controls in the panel will be enabled (if they are in default enabled, shortly fill your panel with enabled controls, let your panel disabled so that your controls will be disabled, too. After enabling panel, your controls will be enabled )

like image 35
icaptan Avatar answered Sep 28 '22 07:09

icaptan