Dynamically adding ToolStripMenuItems to a MenuStrip (C#/ Winforms)

后端 未结 4 1502
小蘑菇
小蘑菇 2021-02-18 18:53

I have my solution implemented (basic solution) and I\'m happy.

Problem is when I add new items to a ToolStripItemCollection using the \'Add\' method, I get a few overl

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-18 19:26

    The way I do it is to create an array of ToolStripMenuItems and populate that array with the items I'm adding. I create one method to handle the click events and have it check something unique about each item I create at run-time. You might try using the Name or Tag properties of each ToolStripMenuItem. Then use AddRange on the spot in the menu you're adding to. So your code might look something like this:

    private void BuildMenuItems()
    {
        ToolStripMenuItem[] items = new ToolStripMenuItem[2]; // You would obviously calculate this value at runtime
        for (int i = 0; i < items.Length; i++)
        {
            items[i] = new ToolStripMenuItem();
            items[i].Name = "dynamicItem" + i.ToString();
            items[i].Tag = "specialDataHere";
            items[i].Text = "Visible Menu Text Here";    
            items[i].Click += new EventHandler(MenuItemClickHandler);
        }
    
        myMenu.DropDownItems.AddRange(items);
    }
    
    private void MenuItemClickHandler(object sender, EventArgs e)
    {
        ToolStripMenuItem clickedItem = (ToolStripMenuItem)sender;
        // Take some action based on the data in clickedItem
    }
    

提交回复
热议问题