I have a ComboBox on a form. The DropDownStyle
property of the ComboBox is set to DropDown
, so that the user can select an item from the drop down list or type in some text manually.
When the user selects an item from the drop down list, I'd like to make some changes to the item's text before it appears in the ComboBox's text field. To use a very simplified example, let's say the drop down list contains items that consist of an ID and a description, like so:
101 Cat
102 Dog
103 Bird
When one of these items is selected, I'd like only the description to appear in the ComboBox's text field. So when "102 Dog" is selected, the string "Dog" should be displayed in the text field, ready to be edited by the user, and the items in the drop down list should be unchanged.
I thought I could just listen to, say, the SelectionChangeCommitted
event of the ComboBox, and set the Text
property of the ComboBox to whatever I like. But if I do this, the changes I make to Text
are ignored, and the entire string ("102 Dog") is still displayed in the ComboBox.
So then I thought I should also update the SelectedIndex
field to -1, to indicate to the ComboBox that the Text
I'm setting is not an item in the drop down list. But this just clears the text field completely, regardless of what I change the Text
property to.
So then I figured that SelectionChangedCommitted
is the wrong event to be using, as it appears to fire too soon for my purposes (the Text
property seems to only be updated with my selection after the SelectionChangeCommitted
event handler has completed). But all other ComboBox events also fail to work, including SelectedIndexChanged
and DropDownClosed
.
I thought this would be pretty trivial to acheive. There's got to be a simple way to do this, and I'm sure I'm missing something obvious... any ideas?
You can try this:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex > -1)
{
string value = comboBox1.Items[comboBox1.SelectedIndex].ToString().Substring(4);
this.BeginInvoke((MethodInvoker)delegate { this.comboBox1.Text = value; });
}
}