Search code examples
c#formswinformsmenu

Enable or disable a menu in a form from another form


I have an application developed in Visual Studio 2022 that works with forms. In this application, there is a main form, from which other forms can be opened. In this main form, there is an item in the top menu ("Selecao"), which must be activated or deactivated depending on which form was opened.

For example, when the "Expenses" form is opened, the menu must be activated (enabled).

When this secondary form is closed, the "Selecao" menu must be disabled. I can enable the menu, but I can’t disable it. I tried to make the main form's menu public in the TelaPrincipal.Designer.cs file:

public System.Windows.Forms.ToolStripMenuItem M_Selecao;

This way, I could disable the menu in the main form when closing the secondary form, but I get an error:

An object reference is required for the method or property 'TelaPrincipal.M_Selecao'

I also don't know how to do it from the main form. Can anyone help me?


Solution

  • Though, I've given my comment on the question, I feel myself tempted to give an answer which gives you another way to achieve what you are expecting.

    From what I am able to understand, you are trying to enable/disable the whole menu item rather than the sub menu items under it. Also, the menu item is already disabled and will be enabled once the form is shown.

    In this case you can create a method like ShowExpensesForm() which will look like this:

    private void ShowExpensesForm()
    {
        ExpensesForm frm = new ExpensesForm();
        frm.Load += (sndr, args) => selacoToolStripMenuItem.Enabled = true;
        frm.FormClosing += (sndr, args) => selacoToolStripMenuItem.Enabled = false;
        frm.Show();
    }
    

    and then you can call it from where you want to show the expenses form like on a click of a button or click of any other menu item and so on.

    Note that I've assumed that enabling and disabling the menu item is the only thing you want when the expenses form opens which is why I used an Inline Event. However, if you want to do much more than that, name your events properly and apply the logic within the scope of those defined events.

    Good luck.