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

后端 未结 4 1518
小蘑菇
小蘑菇 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:16

    I was having similar issues as Philip Wallace. It's important to note the difference between a ToolStripItem, and a ToolStripMenuItem. I was adding ToolStripItems to a ToolStripMenuItem's DropDownItems, and they would show up, and have all properties set correctly, and accessible in code, but they would not show any text! Switching to a ToolStripMenuItem solved this.

    In regards to the original question, I've been using the empty constructor, and setting the fields I needed. (I'm in vb.net with .net 4.0, and it won't let me call New ToolStripMenuItem() since it has a MustInherit tag, so I made this class:

    Public Class DynamicToolStripMenuItem
        Inherits ToolStripMenuItem
    
        Public Sub New(value As Integer, text As String, handler As System.EventHandler)
            MyBase.New()
            Me.Text = text
            Me.Visible = True
            Me.Tag = value
            AddHandler Me.Click, handler
        End Sub
    End Class
    
    0 讨论(0)
  • 2021-02-18 19:20

    You can simply pass null for the image.

    Menu.DropDownItems.Add(Text, null, EventHandler);
    
    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
  • 2021-02-18 19:42

    What is wrong with:

    ToolStripItem item = toolStripItems.Add("MyItem");
    item.Click += new EventHandler(....);
    

    Am I missing something?

    0 讨论(0)
提交回复
热议问题