I just read this article on aspalliance.com by Sandeep Archarya.
I think the article had 2 main points. One was that databinding a combobox is not “bug free” because the act of manually databinding to a combobox causes the SelectedIndexChanged event to fire. The second point was to show how to create a simple namevalue class to be added to the combobox items collection to get around the “problem” of combobox’s taking an object as the item in it’s list (as opposed to a name value pair).
I would point out the following:
First, I am not sure that I would call the SelectedIndexChanged event firing a bug. When you manually databind a list, the first item become selected by default, and thus the selectedindex HAS changed, from -1 to 0.
Second, if you consider this a problem you can get around it a couple different ways.
1) Don’t use manual databinding.
In the designer, select a datasource or create a new one. I created a simple employee object and created an object datasource for this employee. This creates a EmployeeBindingSource object that I bind my employee list to. Using this method, I didn’t experience the SelectedIndexChanged event firing on the databind.
Private list As New System.Collections.Generic.List(Of employee)
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
‘*** create some fake employee objects
For i As Integer = 70 To 80
list.Add(New employee(i, Chr(i)))
Next
‘*** this will populate our control (Combobox1)
Me.EmployeeBindingSource.DataSource = list
End Sub
2) You can use manual databinding, and manually detach and attach the event handler for this event.
Private list As New System.Collections.Generic.List(Of employee)
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
‘*** create some fake employee objects
For i As Integer = 70 To 80
list.Add(New employee(i, Chr(i)))
Next
‘*** remove the handler
RemoveHandler ComboBox1.SelectedIndexChanged, AddressOf ComboBox1_SelectedIndexChanged
‘*** databind
Me.ComboBox1.ValueMember = “id”
Me.ComboBox1.DisplayMember = “name”
Me.ComboBox1.DataSource = list
‘*** add the handler back
AddHandler ComboBox1.SelectedIndexChanged, AddressOf ComboBox1_SelectedIndexChanged
End Sub