Question

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

Was it helpful?

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().

OTHER TIPS

You can add to your MDI container a public method callable from any of its children.
Let's assume that this method is called SetLoggedStatus

(in MDI container)

public void SetLoggedStatus(bool status)
{
    ToolStripMenuItem loginMenu = MenuStrip1.Items(0) as ToolStripMenuItem:
    loginMenu.DropDownItems[0].Text = (status == true ? "Logout" : "Login");
}

Now we need to call this public method from the MDI Child form. Every MDIChild form has a property that points back to the MDIParent We can use that property casting the generic form instance to the correct MDI parent

(in MDIChild after login and supposing the MDIParent is a form class named MyParentForm)

MyParentForm f = this.MDIParent as MyParentForm;
if(f != null) 
    f.SetLoggedStatus(true);

This is how you can access main menu items from an MDI Child:

// this button in the child form
private void button1_Click(object sender, EventArgs e) {  
   ToolStripMenuItem tsm;
   // file menu
   tsm = (ToolStripMenuItem)this.MdiParent.MainMenuStrip.Items[0];
   MessageBox.Show( tsm.DropDownItems[0].Name);
   // first menu under File Menu
   tsm.DropDownItems[0].BackColor = Color.Red;
   // second menu under File Menu
   tsm.DropDownItems[1].BackColor = Color.Wheat;
}

You can change the font or text same way; instead of back color you can use .text.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top