Matt Porterfield
Matt Porterfield

Reputation: 123

How to add already existing ToolStrip Buttons to a ToolStrip Dynamically

I have a Winform Applicaion useing an MDI Form. On the MDI Form I have a ToolStrip with buttons (Buttons have images) on it acting as the main menu buttons for the application. So when user clicks on a button on the toolstrip the mdichild form for that button opens the child form.

So I have six buttons with images already created and in the project. But I want the user to select the buttons they want to appear on the toolstrip. So the user opens the application and there is only one button on the toolstrip. The user clicks on that button and a child screen opens showing all the available existing buttons that could be on the toolstrip. The user selects the buttons they want to appear on the toolstrip then clicks that save button on the child screen.

What I want is that as soon as the user clicks that save button the buttons that the user selected should automatically appear on the toolstrip. Right now I have to have the user close the applicaiton then reopen it for the buttons they selected to appear on the toolstrip.

How so I get the buttons to appear automatically?

Upvotes: 0

Views: 902

Answers (2)

Luis Rodriguez
Luis Rodriguez

Reputation: 14

You can create any ToolStrip and add it to a MenuStrip.DropDownItems.Add. The click EventHandler must be a (s,e) function.

ToolStripMenuItem ts = new ToolStripMenuItem();
ts.Name = $"MyMenuStrip";
ts.Text = "New MenuStrip";
ts.Click += new EventHandler(this.ToolStripMenuItem_Click);

private void ToolStripMenuItem_Click(object sender, EventArgs e)
{
    ToolStripMenuItem clickedMenuItem = sender as ToolStripMenuItem;
    Trace.WriteLine($"Clicked: {clickedMenuItem.Text}");
}

Upvotes: 0

Ken White
Ken White

Reputation: 125748

Just create all of the ToolStripButtons, and set each one's Visible property to false. When the user picks them to be shown, change the Visible property of the ToolStripButton to true. They'll automatically appear on the ToolStrip.

I tested using VS2010 with Oxygene from RemObjects (formerly AKA Delphi Prism).

  • Start a new WinForms application
  • Drop a ToolStrip on the window. Right-click it and choose Insert standard items.
  • Double-click the New button (newToolStripButton, the one on the left end), and add the following code to the newToolStripButton_Click handler:
// Oxygene version: helpToolStripButton.Visible := not helpToolStripButton.Visible;
helpToolStripButton.Visible != helpToolStripButton.Visible;
  • Run the application, and click the newTooStripButton repeatedly, and watch the right-most ToolStripButton (the Help button) appear and disappear from the ToolStrip.

Upvotes: 1

Related Questions