Creating events for clicking on programmatically added menu items?

Screenshot:

enter image description here

I filled the above menu in the screenshot using the code below, but it’s stupid for me, I can’t understand how I can create a click event on each subitem, since they don’t have a property name ?: S My intention is to click, say, “Do and do, "then the file is opened using Process.Start(filename); . Please carry me as I am very new to programming .: | Thank you very 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); } } 
+4
source share
2 answers

Try the click procedure. The sender will be the menu item that was pressed:

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

Then connect the click event for each menu:

 ToolStripItem subItem = new ToolStripMenuItem(); subItem.Click += MenuClicked; subItem.Text = Path.GetFileNameWithoutExtension(file); viewTemplatesToolStripMenuItem.DropDownItems.Add(subItem); 
+9
source

I really don't do window forms, so there might be a more common way to do this, but what you want to do is add an event handler to the click event. Like this:

 subItem.Click += new EventHandler(subItem_Click); 

where subItem_Click will look like this:

 private void subItem_Click(object sender, EventArgs e) { //click logic goes here } 
+2
source

All Articles