Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable controls until a condition is met?

Tags:

c#

loops

winforms

Currently in my program in about 10 control event handlers I have this code:

        if (!mapLoaded)
            return;

When I load a map through the open file dialog I set mapLoaded to true. Another way to do this would be to just disable all the controls for startup and after loading a map to enable all the controls. Unfortunately there are 30+ controls and this is just 30 lines of..

a.Enabled = true;
b.Enabled = true;
c.Enabled = true;

I can't really do a foreach loop through this.Controls either because some of the controls are menustrip items, toolstrip items, panel items, scrollbars, splitters, et cetera and that loop doesn't cover that.

Ideally there would be a way to set every control's enabled property to true in a single and simple loop but I'm not sure of how to do that. Any ideas SO?

like image 250
John Smith Avatar asked Nov 23 '25 05:11

John Smith


1 Answers

Use data binding:

  1. Change mapLoaded into a property that notifies observers when its value has changed...

    public bool MapLoaded
    {
        get
        {
            return mapLoaded;
        }
        set
        {
            if (value != mapLoaded)
            {
                mapLoaded = value;
                MapLoadedChanged(this, EventArgs.Empty);
            }
        }
    }
    private bool mapLoaded;
    
    public event EventHandler MapLoadedChanged = delegate {};
    // ^ or implement INotifyPropertyChanged instead
    
  2. Data-bind your controls' Enabled property to MapLoaded. You can set up the data bindings either using the Windows Forms designer, or using code, e.g. right after InitializeComponent();:

    a.DataBindings.Add("Enabled", this, "MapLoaded");
    b.DataBindings.Add("Enabled", this, "MapLoaded");
    c.DataBindings.Add("Enabled", this, "MapLoaded");
    
like image 191
stakx - no longer contributing Avatar answered Nov 24 '25 17:11

stakx - no longer contributing



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!