简体   繁体   中英

Creating Click Events on Programmatically Added Menu Items?

Screenshot:

在此输入图像描述

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

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

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM