0

I have a form. I've added the strip down button using drag and drop in the form. How can I (in the program) create and fill the toolStripMenu Item? My menu could contain different element...with different names.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
elisa
  • 743
  • 2
  • 13
  • 31

2 Answers2

3

If you want to add items programmatically to a ToolStripDropDownButton just do:

var item1 = new ToolStripButton("my button");
toolStripDropDownButton1.DropDownItems.Add(item1);

var item2 = new ToolStripComboBox("my combo");
toolStripDropDownButton1.DropDownItems.Add(item2);

// etc ...

Instead, if you need to add other ToolStripDropDownButton or other elements directly to you menu (ToolStrip), just do:

var item1 = new ToolStripDropDownButton("my dropdown button");
toolStrip1.Items.Add(item1);

var item2 = new ToolStripProgressBar("my progress bar");
toolStrip1.Items.Add(item2);

// etc ...

EDIT:

You must do it after InitializeComponent() otherwise you won't be able to access to design-time added components, e.g.:

InitializeComponent();

// we're after InitializeComponent...
// let's add 10 buttons under "toolStripDropDownButton1" ...
for (int i = 0; i < 10; i++)
{
    var item = new ToolStripButton("Button_"+i);
    toolStripDropDownButton1.DropDownItems.Add(item);
}
digEmAll
  • 56,430
  • 9
  • 115
  • 140
  • how can i do it in a loop?..THX – elisa Feb 03 '11 at 10:28
  • Basically, add it where you need it. Just add it after `InitializeComponents` otherwise you couldn't access to design-time added components... – digEmAll Feb 03 '11 at 10:35
  • ok..i've added it in the toolStripDropDownButton -> the method that actually appear when you double click the button from the form. Now i have an warning saying that he method System.Windows.Forms.Form.toolStrripDropButton can't be found. I've set the method public ..and i have the same error. WHY?(thx) – elisa Feb 03 '11 at 10:42
  • i'm calling the mthod from initialize component method. It is ok? – elisa Feb 03 '11 at 10:46
  • @mike: The 1st method isn't good because it's a click event handler, InitializeComponent isn't good as well because is designer-generated code... BTW, according to what you said, I think you need more knowledge about WinForms' basis. Look at this good [MSDN Tutorial](http://msdn.microsoft.com/en-us/library/360kwx3z%28v=vs.90%29.aspx) then ask again if you have problems... – digEmAll Feb 03 '11 at 10:47
0

For the DropDown property you need a ContextMenuStrip. The easiest way to find out how to fill it up is to drag&drop one from the toolbox onto your form, fill it up, select it in the DropDown property and afterwards take a look into the Designer.cs file to see how all the stuff is glued together.

The drawback of using the DropDownItems property is that you can't alter some properties like ShowImageMargin.

Oliver
  • 43,366
  • 8
  • 94
  • 151