It seems like when you have a WinForms .NET application, and a ComboBox (set to the "DropDown" style), and that ComboBox has multiple items in it that are identical, weird things happen. Specifically, the index of the selected item can change without firing the SelectedIndexChanged event.
Of course, this causes mass confusion and weird, obscure errors, which is what I've been pulling my hair out over lately.
Here's a simple example you can use to see what I'm talking about:
- Make a new .NET WinForms project (I use VB.NET, but feel free to translate - it's simple enough).
- Drop a ComboBox, a button, and a TextBox (set MultiLine=True) onto the form.
- Use the following code to load the ComboBox with 3 identical items and to print some status messages when the SelectedIndexChanged event fires, and to see what the currently selected index is (via a button):
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
TextBox1.Text = TextBox1.Text & vbNewLine & "ComboBox SelectedIndexChanged event fired." & vbNewLine & _
"SelectedIndex is: " & ComboBox1.SelectedIndex
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
ComboBox1.Items.Add("John Doe")
ComboBox1.Items.Add("John Doe")
ComboBox1.Items.Add("John Doe")
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
TextBox1.Text = TextBox1.Text & vbNewLine & _
"Button clicked." & vbNewLine & _
"SelectedIndex is: " & ComboBox1.SelectedIndex
End Sub
Run the project and select an item from the ComboBox (say, the middle one). Then, click the ComboBox's drop-down arrow, but DON'T SELECT ANYTHING. Click the Button (Button1 by default) and see what it says.
Unless I've lost my mind, here's what you should see:
ComboBox SelectedIndexChanged event fired.
SelectedIndex is: 1
Button clicked.
SelectedIndex is: 0
In other words, the SELECTED INDEX HAS CHANGED but without the SelectedIndexChanged event firing!
This only happens when the items in the ComboBox are identical. If they're different, this doesn't happen. (It also doesn't happen if the ComboBox's "DropDown" style is set to "DropDownList.")
I suspect this may be a bug in the .NET framework itself and not something I can fix, but on the off chance that anyone else has any ideas on what to do here (or what I might be doing wrong!), please chime in! I'm at a loss to explain this behavior or work around it (I expect the SelectedIndex to stay the same unless, y'know, you actually CHANGE it by selecting something else!)
See Question&Answers more detail:
os