How do I automatically add something to a ToolStripMenu, then read the text of that item?

StackOverflow https://stackoverflow.com/questions/12592861

  •  03-07-2021
  •  | 
  •  

Question

Say, for example, I have a ToolStripMenu. I have a tab already made (let's call it Download), and want a substrip of it (the "type here" part) to be automaticaly made. I want it to be text that the string downloadedString is. Then, later, when it's clicked, I want it to fire:

Process.Start("google.com/" + Text of the substrip clicked);

How do I do this?

Was it helpful?

Solution

You can do so via the Click event handler on the ToolStripMenuItem.

Part 1 - programmatically adding menu items

Just add a new ToolStripMenuItem to the MenuStrip like so:

ToolStripMenuItem mi = new ToolStripMenuItem("whatever");
mi.Click += new EventHandler(menuItemHandler_Click);

menuStrip1.Items.Add(mi);

They can all reference the same event handler (see below).

Part 2 - event handler to start your process

The event handler will start the process, using the text of the menu item that was clicked:

private void menuItemHandler_Click(object sender, EventArgs e)
{
    Process.Start("google.com/" + (sender as ToolStripMenuItem).Text);
}

Based on the code above, Process.Start() will receive google.com/whatever as the parameter.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top