Click here to Skip to main content
Click here to Skip to main content

How to add ToolStripMenuItems to a MenuStrip or ContextMenu dynamically

By , 6 May 2011
 
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:
 
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:

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)

About the Author

SercanOzdemir

Turkey Turkey
No Biography provided
Follow on   Twitter   Google+

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralIt 's almost clear.Add ToolstripMenuItem dynamically:/memberSercanOzdemir7-May-11 7:28 
GeneralI hope that this article is not finished. It lacks considera...membermmansf7-May-11 5:59 

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

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130619.1 | Last Updated 6 May 2011
Article Copyright 2011 by SercanOzdemir
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid