Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

How can I synchronize a ToolStripSplitButton's item with the selection?

ToolStripSplitButton.DefaultItem is an easy mechanism to synchronize the click event from the ToolStripSplitButton's item chosen from the dropdown with the one rendered in the button area. This sample assumes you have a click handler associated with each item in the dropdown and have set a default item as part of initialilization.

ToolStripSplitButton veggieButton = new ToolStripSplitButton("Veggies");
veggieButton.DropDownItems.Add("Asparagus");
veggieButton.DropDownItems.Add("Bok Choy");
veggieButton.DropDownItems.Add("Cauliflower");

veggieButton.DisplayStyle = ToolStripItemDisplayStyle.Text;
veggieButton.DropDownItemClicked += new ToolStripItemClickedEventHandler(veggieButton_DropDownItemClicked);
veggieButton.DefaultItemChanged += new EventHandler(veggieButton_DefaultItemChanged);
// menustrip
ToolStrip ts = new ToolStrip();
ts.Items.Add(veggieButton);
this.Controls.Add(ts);
}

void veggieButton_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
((ToolStripSplitButton)sender).DefaultItem = e.ClickedItem;
((ToolStripSplitButton)sender).Text = e.ClickedItem.Text;
}