Search code examples
c#formswinformsmenustrip

How to change protection level of menustrip so I can code in other form where menustrip isn't it


EDIT: If I change in Home Form private to public void then I must do a kinda concvert to bool from void... but I don't know how that works. Can you help me guys?

I am stuck here in the code.... I wanted to know how to access to my other form which has menustrip from another form.

E.G:

I want that clicking on the menustrip from other form where menustrip doesn't exists.

Here is the code:

Form 1

Home frm = new Home();
frm.IsMdiContainer = true;
if(frm.Controls["todasEntradasToolStripMenuItem"].Click += frm.todasEntradasToolStripMenuItem_Click)
       {
            {something}
       }

The form Home is "frm" variable and it is where it has the menu strip. I want help to change the protection level so that this form (Form1) can accept this code... Anyone can help me please?


Solution

  • Solution 1 (nice): Add your Click event in some Init-method or the constructor in Home. There you can access your control.

    todasEntradasToolStripMenuItem.Click += todasEntradasToolStripMenuItem_Click;
    

    Also in Home you define a new event:

        public event EventHandler<EventArgs> TodasEntradasToolStripMenuItemClick;
    
        private void OnTodasEntradasToolStripMenuItemClick(EventArgs e)
        {
            if (todasEntradasToolStripMenuItem != null)
            {
                TodasEntradasToolStripMenuItemClick(this, e);
            }
        }
    

    In the Click handler you raise your own public event:

        private void todasEntradasToolStripMenuItem_Click(object sender, System.EventArgs e)
        {
            OnTodasEntradasToolStripMenuItemClick(e);
        }
    

    In Form1 you add your Handler to this public event:

            Home frm = new Home();
            frm.TodasEntradasToolStripMenuItemClick += frm_TodasEntradasToolStripMenuItemClick;
    

    In this handler you can "do something":

        private void frm_TodasEntradasToolStripMenuItemClick(object sender, EventArgs e)
        {
            // Do something
        }
    

    Solution 2 (do not do it): You asked for changing the protection level. So you can change

    private todasEntradasToolStripMenuItem
    

    in Home to

    internal todasEntradasToolStripMenuItem
    

    or even

    public todasEntradasToolStripMenuItem
    

    But I do not suggest you not to do this. You should choose Solution 1. With Solution 2 you would open Home for more changes than you have to.