65.9K
CodeProject is changing. Read more.
Home

How to add ToolStripMenuItems to a MenuStrip or ContextMenu dynamically

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.50/5 (5 votes)

May 5, 2011

CPOL
viewsIcon

34455

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