How to add things to a menustrip programatically?

后端 未结 2 446

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:25

    You can do this by taking advantage of the object sender parameter in the event handler. Most of this is off the top of my head so I'm only guessing that it will compile but it should get you started.

    void AddMenuItem(string text, string action)
    {
       ToolStripMenuItem item = new ToolStripMenuItem();
       item.Text = text;
       item.Click += new EventHandler(item_Click);
       item.Tag = action;
    
       //first option, inserts at the top
       //historyMenu.Items.Add(item);
    
       //second option, should insert at the end
       historyMenuItem.DropDownItems.Insert(historyMenuItem.DropDownItems.Count, item);
    }
    
    private void someHistoryMenuItem_Click(object sender, EventArgs e)
    {
       ToolStripMenuItem menuItem = sender as ToolStripMenuItem;
    
       string args = menuItem.Tag.ToString();
    
       YourSpecialAction(args);
    }
    

提交回复
热议问题