Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Items to ToolStrip at RunTime

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?

like image 610
ikathegreat Avatar asked May 17 '12 06:05

ikathegreat


2 Answers

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();
    }
like image 146
yahya kh Avatar answered Oct 20 '22 09:10

yahya kh


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);
}
like image 26
GodLesZ Avatar answered Oct 20 '22 07:10

GodLesZ