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

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

Comments

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.