Search code examples
c#winformsmdimenustrip

How do I change a menuStrip menu text from child window?


I need to change a menuStrip item text of the main window (mdi container) from a child window,

something like this:

File
-Login

to

File
-Logout


Solution

  • On the main window add these:

    public static MainForm Current;
    
    public string FileLogin
    {
        get { return fileLoginToolStripMenuItem.Text; }
        set { fileLoginToolStripMenuItem.Text = value; }
    }
    

    Obviously use the name that you set or was automatically set for the menu strip item for the login/logout menu item. then in the form constructor of the main form, set the Current.

    public MainForm()
    {
        InitializeComponent();
        Current = this;
    }
    

    Then from the other window/form you can call (to set the value):

    MainForm.Current.FileLogin = "Logout";
    

    But better than this is that you on your child window make an event,

    public event Action UserLoggedIn = delegate { };
    

    And on the MainForm have the MainForm subscribe to that event with a reverse of the above...

    ChildForm.Current.UserLoggedIn += () => FileLogin = "Logout";
    

    And have the child raise the event when the user logs in, with UserLoggedIn().