How to add things to a menustrip programatically?
Asked Answered
Q

2

8

I want to add whatever is written in a textbox to a menustrip. In the File > Recent Searches thing I have.

How can I do programatically? And can I assign an event handler dynamically so that when a user clicks on X item in that subfolder, the text is copied BACK to the textbox?

EDIT: How can I programatically call on the folder Busquedas Recientes (in pic)

alt text

Quincey answered 22/10, 2009 at 15:39 Comment(1)
Which IDE or platform/language are you using? (for example, C with Win32 API, C# on .NET Framework, or etc.)Antoneantonella
Y
10

You can do this by taking advantage of the object sender parameter in the event handler. Most of this is off the top of my head so I'm only guessing that it will compile but it should get you started.

void AddMenuItem(string text, string action)
{
   ToolStripMenuItem item = new ToolStripMenuItem();
   item.Text = text;
   item.Click += new EventHandler(item_Click);
   item.Tag = action;

   //first option, inserts at the top
   //historyMenu.Items.Add(item);

   //second option, should insert at the end
   historyMenuItem.DropDownItems.Insert(historyMenuItem.DropDownItems.Count, item);
}

private void someHistoryMenuItem_Click(object sender, EventArgs e)
{
   ToolStripMenuItem menuItem = sender as ToolStripMenuItem;

   string args = menuItem.Tag.ToString();

   YourSpecialAction(args);
}
Yuhas answered 22/10, 2009 at 15:46 Comment(1)
The first method kinda works. The search is being added but on the top most level. I need it to be added into this heirarchy: File > RecentSearches > THINGS GO HERE. Any help?Quincey
P
5

It's rather straight forward. You can do the following:

ToolStripMenuItem menuItem

foreach (string text in collectionOfText)
{
    ToolStripMenuItem foo = new ToolStripMenuItem(text);
    foo.Click += new EventHandler(ClickEvent);
    menuItem.DropDownItems.Add(foo);
}

Subsequently, if the Click event doesn't work (I had trouble where it wouldn't detect the correct menu item), you can add a "DropDownItemClicked" event to the menuItem. and to get the text of the item you clicked you do:

private void DropedDownItemClickedEvent(object sender, ToolStripItemClickedEventArgs e)
{
    string text = e.ClickedItem.Text;
}

I hope that helps.

Oh and don't forget to remove the Event as well. I forgot to do that with all the dynamic menus I had created and somehow ended up eating half my memory. :D

Pricefixing answered 22/10, 2009 at 16:0 Comment(1)
Lol. :P +1 for the last comment. Saved me another question xDQuincey

© 2022 - 2024 — McMap. All rights reserved.