5

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);
    }
}
merv
  • 331
  • 5
  • 25

2 Answers2

10

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);
LarsTech
  • 80,625
  • 14
  • 153
  • 225
2

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
}
Phillip Schmidt
  • 8,805
  • 3
  • 43
  • 67