vb.neteventsevent-handlingcontrolsselectedindexchanged

VB.NET: SelectedIndexChanged firing multiple times


I am trying to programmatically add an unspecified amount of new UserControls to a form. One will be added every time an entry is selected in a ComboBox contained within the UserControl.

Problem is, the SelectedIndexChanged event fires completely erratically. Sometimes twice, sometimes 3 times, etc., but never just once. No matter how many times I set the combobox's SelectedIndex to -1, it fires at least once with a SelectedIndex of 0. Sometimes the Itemselected event fires multiple times inbetween SelectedIndexChanged events.

InvoiceEntry.vb snippet:

Public Event ItemSelected As EventHandler
Private Sub cboItem_SelectedIndexChanged(sender As System.Object, _
            e As System.EventArgs) Handles cboItem.SelectedIndexChanged
    RaiseEvent ItemSelected(Me, EventArgs.Empty)
End Sub

Invoice.vb snippet:

Private numEntries As Integer = 1

Public Sub invEntry1_ItemSelected() Handles invEntry1.ItemSelected
    numEntries += 1

    Dim newEntry As InvoiceEntry = invEntry1
    Dim pt As Point = newEntry.Location
    pt.Y += 30

    newEntry.Location = pt
    newEntry.Name = "invEntry" + numEntries.ToString

    pnlEntries.Controls.Add(newEntry)

End Sub

I'm at a complete loss as to what is wrong. Please let me know if you need more information, as I will be monitoring this thread until I or someone else figures it out.


Solution

  • As far as I know, when you add new combo box the selected index is changing at this time (this is when it triggers first time). It will also trigger every time you programatically change a value.

    If you want to generate controls after user has selected something from the combo box try using

    ComboBox.SelectionChangeCommitted
    

    http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.selectionchangecommitted.aspx