How to add things to a menustrip programatically?

后端 未结 2 420

I want to add whatever is written in a textbox to a menustrip. In the File > Recent Searches thing I have.

How can I do programatically? And can I assign an event ha

2条回答
  •  伪装坚强ぢ
    2021-01-05 02:21

    It's rather straight forward. You can do the following:

    ToolStripMenuItem menuItem
    
    foreach (string text in collectionOfText)
    {
        ToolStripMenuItem foo = new ToolStripMenuItem(text);
        foo.Click += new EventHandler(ClickEvent);
        menuItem.DropDownItems.Add(foo);
    }
    

    Subsequently, if the Click event doesn't work (I had trouble where it wouldn't detect the correct menu item), you can add a "DropDownItemClicked" event to the menuItem. and to get the text of the item you clicked you do:

    private void DropedDownItemClickedEvent(object sender, ToolStripItemClickedEventArgs e)
    {
        string text = e.ClickedItem.Text;
    }
    

    I hope that helps.

    Oh and don't forget to remove the Event as well. I forgot to do that with all the dynamic menus I had created and somehow ended up eating half my memory. :D

提交回复
热议问题