- List Box. Selected Index Changed Событие
- Определение
- Тип события
- Примеры
- Комментарии
- Combo Box. Selected Index Свойство
- Определение
- Значение свойства
- Исключения
- Примеры
- Комментарии
- Why does ComboBox.SelectedIndexChanged event fire three times before form load?
- WinForms ComboBox SelectedIndexChanged not firing when typing few chars followed by Alt+Down
List Box. Selected Index Changed Событие
Определение
Происходит при изменении свойства SelectedIndex коллекции SelectedIndices. Occurs when the SelectedIndex property or the SelectedIndices collection has changed.
Тип события
Примеры
В следующем примере кода показано, как использовать SelectedIndexChanged событие для поиска и выбора элемента в другом ListBox элементе управления. The following code example demonstrates how to use the SelectedIndexChanged event to search for and select an item in a different ListBox control. В примере с помощью SelectedIndexChanged события определяется, когда изменяется выбранный элемент в ListBox . The example uses the SelectedIndexChanged event to determine when the selected item in the ListBox is changed. Затем пример кода считывает текст элемента с помощью SelectedItem Свойства и вызывает FindString метод для другого, ListBox используя текст, возвращенный SelectedItem в первом ListBox . The example code then reads the text of the item using the SelectedItem property and calls the FindString method on a different ListBox using the text returned by SelectedItem in the first ListBox. Если элемент найден в другом элементе, он ListBox выбирается. If an item is found in the other ListBox, the item is selected. В этом примере необходимо, ListBox listBox1 чтобы в форму были добавлены два элемента управления с именами и listBox2 , а оба ListBox элемента управления содержат одинаковые элементы. This example requires that two ListBox controls, named listBox1 and listBox2 , have been added to a form and that both ListBox controls contain items that are identical. В этом примере также требуется, чтобы метод обработки событий, определенный в примере, был подключен к SelectedIndexChanged событию listBox1 . The example also requires that the event-handling method defined in the example is connected to the SelectedIndexChanged event of listBox1 .
Комментарии
Можно создать обработчик событий для этого события, чтобы определить, когда был изменен выбранный индекс в ListBox . You can create an event handler for this event to determine when the selected index in the ListBox has been changed. Это может быть полезно, если необходимо отобразить сведения в других элементах управления на основе текущего выбора в ListBox . This can be useful when you need to display information in other controls based on the current selection in the ListBox. Обработчик событий для этого события можно использовать для загрузки сведений в другие элементы управления. You can use the event handler for this event to load the information in the other controls.
Если SelectionMode свойство имеет значение SelectionMode.MultiSimple или SelectionMode.MultiExtended , любое изменение в SelectedIndices коллекции, включая удаление элемента из выбора, вызовет это событие. If the SelectionMode property is set to SelectionMode.MultiSimple or SelectionMode.MultiExtended, any change to the SelectedIndices collection, including removing an item from the selection, will raise this event.
Дополнительные сведения об обработке событий см. в разделе обработка и вызов событий. For more information about handling events, see Handling and Raising Events.
Combo Box. Selected Index Свойство
Определение
Возвращает или задает индекс, указывающий текущий выделенный элемент. Gets or sets the index specifying the currently selected item.
Значение свойства
Индекс текущего выделенного элемента (индексация ведется с нуля). A zero-based index of the currently selected item. Если элемент не выбран, возвращается отрицательное значение (-1). A value of negative one (-1) is returned if no item is selected.
Исключения
Указанный индекс меньше или равен -2. The specified index is less than or equal to -2.
Указанный индекс больше или равен числу элементов в поле со списком. The specified index is greater than or equal to the number of items in the combo box.
Примеры
В следующем примере кода показано, как использовать FindString метод и SelectedIndex свойство. The following code example show how to use the FindString method and SelectedIndex property. Пример является частью полного примера в ComboBox обзоре класса. The example is part of a complete example in the ComboBox class overview.
Комментарии
This property indicates the zero-based index of the currently selected item in the combo box list. Setting a new index raises the event.
Если FormattingEnabled параметр имеет значение false , то SelectedIndex параметр не будет установлен равным-1, если SelectedValue является пустым. If FormattingEnabled is false , SelectedIndex will not be set to -1 when SelectedValue is blank.
Если FormattingEnabled параметр имеет значение true , то SelectedIndex параметр будет установлен равным-1, если SelectedValue пуст. If FormattingEnabled is true , SelectedIndex will be set to -1 when SelectedValue is blank.
Чтобы отменить выбор текущего выбранного элемента, задайте для параметра значение SelectedIndex -1. To deselect the currently selected item, set the SelectedIndex to -1. Нельзя задать SelectedIndex ComboBox для элемента значение-1, если элемент является элементом с привязкой к данным. You cannot set the SelectedIndex of a ComboBox item to -1 if the item is a data-bound item.
Why does ComboBox.SelectedIndexChanged event fire three times before form load?
I have a little problem with combobox databinding. I have a form that has one combobox and based on the selection in the ComboBox the form should be filled with data. I use the SelectedIndexChanged event instead of SelectionChangeCommitted because I want to be able to fill the form with the data of the first item in the ComboBox when the form loads. I have tried 2 solutions:
- Add the event handler before Data Binding.
This solution almost works as it should. It selects the first ComboBox item and fills the form with relevant data but for some reason this event fires three times when binding data and this makes the form loading slow because some data gets called from a database and basically this data is being loaded 3 times.
- Add the event handler after Data Binding.
This solution doesn’t work like I’d want to because it doesn’t fill the form with the relevant data although the first item is correctly selected in the ComboBox after form load. This is mainly because I add the event handler (fills the form with data) after the Data Binding is done. The good thing about this solution is that the event is not being fired 3 times in a row, but that’s the only good thing about this solution because the form is not being filled with relevant data like intended.
Does anyone have any idea why this event is getting fired 3 times? As a possible way to fix the problem I could call the method, that should be fired by the event, after Data Binding and then add event handler to the ComboBox, but this looks like a hackish way of doing things. If someone can provide a better way to get things done I’d be really happy. However, if my solution happens to be the only/best way of doing things, then can someone maybe tell me technical reasons for the event firing multiple times during Data Binding?
EDIT: I guess I found the reason and solution already. The reason the event got fired 3 times wasn’t that data binding fired it 3 times — it was because assigning DisplayMember and ValueMember fired this event too.
WinForms ComboBox SelectedIndexChanged not firing when typing few chars followed by Alt+Down
In short
When I type a character in a ComboBox, press Alt+Down followed by Enter or Tab, the SelectedIndexChanged event doesn’t fire, even though the SelectedIndex value does change! Why doesn’t the event fire?
Update The same error occurs if you type a character, press Alt+Down and then type Esc. You would expect the Esc to cancel the change. However, the SelectedIndex does change, and the SelectedIndexChanged event doesn’t fire.
What should happen if you just type Alt+Down, use the arrow keys to browse to an entry, and then type Esc? Should the selected index be set back to its original value?
Not so short
I have a WinForm application with a ComboBox on it. The ComboBox’ SelectedIndexChanged event is wired up to a event handler that shows the SelectedItem in a Label control. The ComboBox’ Items collection has three values: «One», «Two», and «Three».
- When I select an item with the mouse, the event fires.
- When I scroll the mouse, the event fires.
- When I use Alt+Down to expand the combobox and walk through the items with Up and Down, the event fires.
- But. When I type in the first character of a value, then press Alt+Down, followed by Enter or Tab, the value does get selected and is shown in the combobox, but the event doesn’t fire.
I’ve also added a button that shows the SelectedIndex. It shows the SelectedIndex has changed. So even though the SelectedIndex does change, the SelectedIndexChanged event does not fire!
If I just type in a valid value like One the event doesn’t fire either, but in that case a click on the button reveals the SelectedIndex indeed hasn’t changed. So in that case the behavior is normal.
To reproduce, create a Form and add a ComboBox, a Label and a Button. Place the following code in the Form1.cs: