Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Click Events on Programmatically Added Menu Items?

Tags:

c#

winforms

Screenshot:

enter image description here

I populated the above menu in screenshot using below code, but silly me I can't figure out how can I create click event on each subitem since they don't have property name? :S My intention is to click, let say, "Do and Do", then the file will be opened using Process.Start(filename);. Please bear with me as I am very new to programming. :| Thank you so much!

private void loadViewTemplates(string path)
{
    foreach (string file in Directory.GetFiles(path, "*.txt"))
    {
        ToolStripItem subItem = new ToolStripMenuItem();
        subItem.Text = Path.GetFileNameWithoutExtension(file);
        viewTemplatesToolStripMenuItem.DropDownItems.Add(subItem);
    }
}
like image 666
merv Avatar asked Aug 20 '12 23:08

merv


2 Answers

Try stubbing out the click procedure. The sender would be the menu item that was clicked:

private void MenuClicked(object sender, EventArgs e) {
  MessageBox.Show("Clicked on " + ((ToolStripMenuItem)sender).Text);
}

Then wire up the click event for each menu:

ToolStripItem subItem = new ToolStripMenuItem();
subItem.Click += MenuClicked;
subItem.Text = Path.GetFileNameWithoutExtension(file);
viewTemplatesToolStripMenuItem.DropDownItems.Add(subItem);
like image 161
LarsTech Avatar answered Sep 29 '22 11:09

LarsTech


I don't really do windows forms, so there may be a more universally accepted way to do this, but what you want to do here is add an event handler to the "click" event. Like this:

subItem.Click += new EventHandler(subItem_Click);

where subItem_Click would look like this:

private void subItem_Click(object sender, EventArgs e)
{
    //click logic goes here
}
like image 40
Phillip Schmidt Avatar answered Sep 29 '22 12:09

Phillip Schmidt