Creating a DropDownButton / SplitButton which shows the selected item’s text
| Product Version | Product | Author | Last modified |
|---|---|---|---|
| Q2 2007 | RadControls for WinForms | Angel Kanchev | August 13, 2007 |
HOW-TO
Create a DropDownButton / SplitButton which shows the selected item’s text
DESCRIPTION
This KB article describes a way to show a DropDownButton item’s text in the button itself, after the item has been clicked. It also applies to the SplitButton control.
SOLUTION
- Subscribe to the Click event for all menu items in the DropDownButton that have no subitems.
- Subscribe for Load and FormClose events of the Form and fill them like this:
private void Form1_Load(object sender, EventArgs e)
{
RadDropDownButtonElement buttonElement = (RadDropDownButtonElement)this.radDropDownButton1.RootElement.Children[0];
SubscribeMenuItems(buttonElement.DropDownMenu.Items);
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
RadDropDownButtonElement buttonElement = (RadDropDownButtonElement)this.radDropDownButton1.RootElement.Children[0];
UnsubscribeMenuItems(buttonElement.DropDownMenu.Items);
}
- Add the private methods that will recursively subscribe / unsubscribe for Click event for every menu item that has no subitems:
private void SubscribeMenuItems(RadItemCollection menuItems)
{
for (int i = 0; i < menuItems.Count; i++)
{
RadMenuItem subMenuItem = menuItems[i] as RadMenuItem;
if (subMenuItem != null)
{
if (subMenuItem.Items.Count == 0)
subMenuItem.Click += new EventHandler(DropDownMenuItem_Click);
else
SubscribeMenuItems(subMenuItem.Items);
}
}
}
private void UnsubscribeMenuItems(RadItemCollection menuItems)
{
for (int i = 0; i < menuItems.Count; i++)
{
RadMenuItem subMenuItem = menuItems[i] as RadMenuItem;
if (subMenuItem != null)
{
if (subMenuItem.Items.Count == 0)
subMenuItem.Click -= new EventHandler(DropDownMenuItem_Click);
else
UnsubscribeMenuItems(subMenuItem.Items);
}
}
}
private void DropDownMenuItem_Click(object sender, EventArgs e)
{
RadMenuItem clickedMenuItem = (RadMenuItem)sender;
this.radDropDownButton1.Text = clickedMenuItem.Text;
}
The event handler DropDownMenuItem_Click() does the job here - the text of the DropDown button is set to the text of the clicked menu item.
Note that the subscription for Click must be synchronized with the menu items. If a menu item is added DropDownMenuItem_Click() must be added to its Click event. If a menu item is removed its Click event must be unsubscribed. For simplicity (and when the menu items are not too many) before modification of the menu items can be called UnsubscribeMenuItems() and after the modification - SubscribeMenuItems().