Reputation: 3214
There are lots of values in my combobox and they are ordered by alphabetically. When I press a letter to select a value that I want selectedindexchanged and selectedvaluechanged events are fired but I don't want this. Actually I didn't select the value yet. I am trying to reach the value that I want to select. Why is this? How can we prevent this?
AUDI
BMW
CITROEN
D...
E...
MERCEDES -> To select this. pressing M fires events???
OPEL
VOLVO
Upvotes: 0
Views: 489
Reputation: 2263
selected index changes if you choose something or turns -1 if the current text is not a item from its list. which can be a result of changing the text
value change basically fires because text changed no matter if its in the list or not.
Its not exactly clear to me what you want to do; but maybe you want to combine the behaviour, so only fall trough your code; pseudo code like this:
inside your value changedevent()
{
// first you might put in some text reformating code here
// so for example you might replace spaces for '-' or so..
// or if one presses M,(and text length =1
// the list of elements in the control
// could be filtered on items starting with an M
// by using a Linq query or so on a list or array.
If (yourcombobox.selectedindex > -1) {// fire my code as now we're sure its an existing element}
}
Upvotes: 0
Reputation: 4352
If you don't want to create new user control or handle this in the event handler, you can use AutoCompleteSource property of combo box. This will raise the SelectedIndexChanged when the user completed his selection by using enter button or control lost the focus or user selects the item using mouse click. For achieve this, set the following properties to the combo box.
this.comboBox.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
this.comboBox.AutoCompleteSource = AutoCompleteSource.ListItems;
List<string> testString = new List<string>{"abcd", "acde", "adef", "bcde", "bdef", "befg", "cdef", "defg", "cfgh"};
this.comboBox.DataSource = testString;
this.comboBox.SelectedIndexChanged += this.ComboBoxOnSelectedIndexChanged;
Upvotes: 0
Reputation: 4352
In your SelectionChanged event handler, you can handle this by setting e.Handled = true when your ComboBox popup is open. If the popup is closed, you can continue the actual steps you want to execute in your SelectionChanged event.
Or else you could make your own custom control that inherits from ComboBox. In the constructor for that class, add an event handler for SelectionChanged and mark the event as handled by setting e.Handled = true when your popup is open. You may have to play around with which events you're subscribing to/marking as handled in your custom control to get things behaving exactly the way you want.
Note: You can check whether the combobox popup is opened or not by handling the DropDown and DropDownClosed event. :-)
Upvotes: 1