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:
1 | Private Sub xfrm_Load( ByVal sender As Object , ByVal e As System.EventArgs) Handles Me .Load |
2 | xCombo.DataSource = GetSomeData() |
3 | xCombo.SelectedIndex = -1 |
Then, when user actually selects an item – SelectedIndexChanged event handler is called to perform action on the selected item:
1 | Private Sub xCombo_SelectedIndexChanged( ByVal sender As System. Object , ByVal e As System.EventArgs) Handles xCombo.SelectedIndexChanged |
2 | PerformSomeAction(xCombo.SelectedValue) |
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:
1 | Private Sub xCombo_SelectedIndexChanged( ByVal sender As System. Object , ByVal e As System.EventArgs) |
2 | PerformSomeAction(xCombo.SelectedValue) |
and programmaticaly assign even handler to the combobox event:
1 | Private Sub xfrm_Load( ByVal sender As Object , ByVal e As System.EventArgs) Handles Me .Load |
2 | xCombo.DataSource = GetSomeData() |
3 | xCombo.SelectedIndex = -1 |
4 | AddHandler xCombo.SelectedIndexChanged, AddressOf xCombo_SelectedIndexChanged |
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.