Click here to Skip to main content
15,878,748 members
Articles / Programming Languages / C#
Tip/Trick

How to add ToolStripMenuItems to a MenuStrip or ContextMenu dynamically

Rate me:
Please Sign up or sign in to vote.
3.50/5 (5 votes)
6 May 2011CPOL 33.5K   4   2
Think about the Office Word application's file menustrip. The files which you last open are listed there. How is this possible? Here is the code:

C#
ToolStripMenuItem NEW;
NEW = new ToolStripMenuItem(text);
NEW.Text = text;
NEW.Click += new EventHandler(Item_Click);
NEW.CheckOnClick = true;
MainToolStripMenuItem.DropDown.Items.Add(NEW);

Then you can use the Click event like:


C#
private void Item_Click(object sender, EventArgs e)
{
    if (sender is ToolStripMenuItem)  //Check On Click.
    {
        foreach (ToolStripMenuItem item in (((ToolStripMenuItem)sender).GetCurrentParent().Items))
        {
            if (item == sender)
            {
                txtNoteName.Text = item.Text;
                item.Checked = true;
            }
            if ((item != null) && (item != sender))
                item.Checked = false;
            }
        }
    }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader
Turkey Turkey
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralIt 's almost clear.Add ToolstripMenuItem dynamically:/ Pin
SercanOzdemir7-May-11 7:28
SercanOzdemir7-May-11 7:28 
GeneralI hope that this article is not finished. It lacks considera... Pin
mmansf7-May-11 5:59
mmansf7-May-11 5:59 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.