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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With