Delaying SelectedIndexChanged event of ComboBox in VB.NET WinForm

A standard situation – ComboBox control of VB.NET WinForm is populated with some data in Form_Load event and index is set to -1 so no item is selected:

Private Sub xfrm_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
   xCombo.DataSource = GetSomeData()
   xCombo.SelectedIndex = -1
End Sub

Then, when user actually selects an item – SelectedIndexChanged event handler is called to perform action on the selected item:

Private Sub xCombo_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles xCombo.SelectedIndexChanged
   PerformSomeAction(xCombo.SelectedValue)
End Sub

The problem with this approach is when data is bound in Form_Load – SelectedIndexChanged event handler is also called, and when SelectedIndex is set to -1, SelectedIndexChanged event is called again. Since we expect the SelectedIndexChanged to run only when user selects an item – this behavior may cause unwanted consequences.

The solution is to remove Handles VB.NET keyword from event handler declaration:

Private Sub xCombo_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
   PerformSomeAction(xCombo.SelectedValue)
End Sub

and programmaticaly assign even handler to the combobox event:

Private Sub xfrm_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
   xCombo.DataSource = GetSomeData()
   xCombo.SelectedIndex = -1
   AddHandler xCombo.SelectedIndexChanged, AddressOf xCombo_SelectedIndexChanged
End Sub

In this case when data is bound to the combobox and SelectedIndex is assigned a value – no event handler is associated with SelectedIndexChanged event. And only after those actions are performed – event handler is added, so the next time user selects an item action is performed.

Leave a Reply

Your email address will not be published. Required fields are marked *