Adding Items to ToolStrip at RunTime

不想你离开。 提交于 2019-12-07 04:46:39

问题


Hello I have a ToolStripMenu with a "Favorites" menu that I want to add sub items to during my WinForms app at run time. I have a datagridview that I right click on to show a context menu that has an "Add to Favorites" option. When that event is fired, I'd like to add an item using maybe some text from the selected row from the datagriview (this I know how to do already) to this Favorites menu. The tricky part to is I need to create code for my newlyCreatedToolStripMenuItem_Click event. I will determine how to save my favorites list later.

So we're going for:

Right click datagridview row for "John Smith"

Choose "Add to Favorites" from ContextMenu

The Favorites ToolStripMenu has a new item added to it that reads "John Smith"

Clicking the "John Smith" ToopStripMenuItem fires an action (such as select that row in the daragridview row, etc.)

Any good starting ideas?


回答1:


If i understand you right, i guess that this is exactly what you want:

    private void buttonAddFav_Click(object sender, EventArgs e)
    {
        ToolStripItem item = new ToolStripMenuItem();
        //Name that will apear on the menu
        item.Text = "Jhon Smith";
        //Put in the Name property whatever neccessery to retrive your data on click event
        item.Name = "GridViewRowID or DataKeyID";
        //On-Click event
        item.Click += new EventHandler(item_Click);
        //Add the submenu to the parent menu
        favToolStripMenuItem.DropDownItems.Add(item);
    }

    void item_Click(object sender, EventArgs e)
    {
        throw new NotImplementedException();
    }



回答2:


This is quite simple. You just have to setup a callback method which is used for all favorite ToolStripMenuItem's. In this method you compare the item.Text or item.Name attributes and execute the different favorite methods.

private void FavoriteToolStriptem_Click(object sender, EventArgs e) {
    ToolStripMenuItem item = sender as ToolStripMenuItem;
    MessageBox.Show("You clicked on the menu item called " + item.Name + " shown as " + item.Text);
}


来源:https://stackoverflow.com/questions/10630828/adding-items-to-toolstrip-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!