Reader Level:
ARTICLE

How to create a "ComboBox button" in a toolbar in .NET

Posted by Mike Gold Articles | Windows Controls C# November 20, 2001
You can actually put a ComboBox in your toolbar by just dragging a ComboBox from the toolbox onto the toolbar but if you want the ComboBox to be one of the toolbar buttons, you are out of luck using the regular old ComboBox. One way around this is to use the DropDownMenu style of a ToolbarButton to create a pseudo-ComboBox.
  • 0
  • 0
  • 40980
Download Files:
 

 

Figure 1 - The toolbar ComboBox

This article was written in response to a question in the C# Corner Forum.  The question was:   "How do I put a combobox in a toolbar,  Help!" You can actually put a ComboBox in your toolbar by just dragging a ComboBox from the toolbox onto the toolbar, but if you want the ComboBox to be one of the toolbar buttons, you are out of  luck using the regular old ComboBox.  One way around this is to use the DropDownMenu style of a ToolbarButton to create a pseudo-ComboBox. 

The Toolbar allows three styles of buttons in .NET.  The styles and descriptions are shown in the table below:

ToolbarButtonStyle Description
PushButton Button bounces back after you press it and triggers an OnClick event
ToggleButton A Button that maintains 2 states: pressed in and pressed out
Separator  A space or line between buttons to separate them.  Change the Appearance property to change what the separator displays
DropDownButton Allows you to put a context menu in your toolbar

Our color menu uses the style DropDownButton and attaches the context menu we provide that contains the list of 'items' for the ComboBox.  The diagram below shows the property window for the DropDownButton in the Toolbar:

 

DropDownButton Property Window

MyContext Menu is simply a regular old ContextMenu which we can drag from the toolbox onto our form. The ContextMenu contains the colors as menu items.  The ContextMenu in the Form Design View is shown below:

ContextMenu in Design View

If you double click on each menu item, you get an EventHandler corresponding to the color that you can populate in your code.  To get our ComboBox behavior, we simply take advantage of the EventHandler to change the ToolBar Text of our DropDownButton.  Below is the code for the "red" event handler.  The other colors are virtually the same code for the event handler:

private void menuItem1_Click(object sender, System.EventArgs e)
{
  MenuItem TheItem = (MenuItem)sender;  // get a hold of the MenuItem
   string theText = TheItem.Text;   // get the color from the menu
   toolBarButton1.Text = Pad(theText);   //  set the ToolBar Text equal to the Menu Text plus some padding
}

Make sure you put the menu on the end of the toolbar, otherwise it looks strange when it resizes the toolbar when it changes the text.

COMMENT USING

Trending up