Search code examples
c#winformsmenustrip

Activating something from a menu strip doesn't work


I have a button on Form1 that starts disabled by default. I have a ConfigureForm, where I have a menu strip, with an option to enable the button in Form1.

So my code is:

    private void Portal2HammerButtonEnable_Click(object sender, EventArgs e)
    {
        Form1 frm1 = new Form1();
        frm1.Portal2HammerButton.Enabled = true;
    }

But when I close ConfigureForm and look at the button, it's still disabled.


Solution

  • That's because you create a new Form1 and enable on that form the button. Instead, you have to pass the instance of the form you actually have open.

    For design purposes you may want to use a controller class between these two forms. This will help you to simplify the complexity of passing data or actions between the two forms and will give you the power to escalate better the app..

    When you open the ConfigureForm you have to do the following (in the simplest form however not recommended.)

    ...
    {
        ConfigureForm frmConfigure = new ConfigureForm(this);
    }
    

    Then inside the ConfigureForm:

    public partial class ConfigureForm : Form
    {
        private From1 mainForm = null;
    
        public ConfigureForm()
        {
            InitializeComponent();
        }
    
        public ConfigureForm(Form callingForm):this()
        {
            mainForm = callingForm as Form1;
        }
    
        private void Portal2HammerButtonEnable_Click(object sender, EventArgs e)
        {
            mainForm.Portal2HammerButton.Enabled = true;
        }
    }