Adding Items to ToolStrip at RunTime

ikathegreat picture ikathegreat · May 17, 2012 · Viewed 19.6k times · Source

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?

Answer

yahya kh picture yahya kh · May 17, 2012

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();
    }