Tuesday, December 7, 2010

Add Menus and Submenus Dynamically

I devote this post to menu controls in C# and show how to add menus and submenus during runtime, since I got the impression that this is not so clearly understandable.
I show here methods using some extra stuff, so who knows more direct code, please tell me.
Aim of the sample program will be to create the following menu structure:


First we add a control of the type menuStrip to the form using the designer (of course this also can be dynamically, see add controls during runtime).
Now in the form a yet invisible menu bar is created, which is still empty. In the designer you could now write in this bar to add menus, but we focus on the dynamic part.
Super menus, so menus on the highest level in the menu bar (e.g. "Obermenü 1" and "Obermenü 2") can be edited with the property Items of the class menuStrip.




The following code commands create 2 supermenus:

menuStrip1.Items.Add("Obermenü 1");
menuStrip1.Items.Add("Obermenü 2");

Using indicces (e.g. menuStrip1.Items[0]) we can access these menuentries, but we cannot create submenus in them.
For that we have to convert the object explicitely to an object of the type ToolStripMenuItem. This now has the property DropDownItems, with which we can create submenus.
To create the submenus "Untermenü 1" and "Untermenü 2" for example, we run the following code

((ToolStripMenuItem)menuStrip1.Items[0]).DropDownItems.Add("Untermenü 1");       
((ToolStripMenuItem)menuStrip1.Items[0]).DropDownItems.Add("Untermenü 2");

This submenus right now are not accessible any more. But we need them, if we want to create more submenus, which open to the right (in the example "rechtes Untermenü 1" and "rechtes Untermenü 2").
Therefore, we just save the submenu when creating in a variable of type ToolStripMenuItem, e.g. like this:

ToolStripMenuItem Untermenue1 = (ToolStripMenuItem)((ToolStripMenuItem)menuStrip1.Items[0]).DropDownItems.Add("Untermenü 1");

(In front of the assignment again an explicite type conversion has to happen.)
Now we have continous access to the desired submenu, and can add own submenus to it with DropDownItems.Add().
Finally the complete soure code:

            menuStrip1.Items.Add("Obermenü 1");
            menuStrip1.Items.Add("Obermenü 2");

            ToolStripMenuItem Untermenue1 = (ToolStripMenuItem)((ToolStripMenuItem)menuStrip1.Items[0]).DropDownItems.Add("Untermenü 1");
            ((ToolStripMenuItem)menuStrip1.Items[0]).DropDownItems.Add("Untermenü 2");

            Untermenue1.DropDownItems.Add("rechtes Untermenü 1");
            Untermenue1.DropDownItems.Add("rechtes Untermenü 2");

No comments:

Post a Comment