How to add ToolStripMenuItems to a MenuStrip or ContextMenu dynamically






3.50/5 (5 votes)
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;
}
}
}