Click here to Skip to main content
15,905,233 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:

In my code I'm using the SelectedIndexChanged event of listboxes. I had to find out that this event seems to be automatically raised while the listbox gets filled with it's elements.

First of all, after the listbox has been filled I want to have no item selected. I'm currently doing this with "ctrl.SelectedItem = Nothing", but somehow I have the feeling that's not really elegant. Maybe you have a better idea or good practice I can learn on this.

The main concern of my question is: Is there a way to suppress the SelectedIndexChanged event while the listbox hasn't been filled? Which would that be?

Thank you for any hints.

Kind Regards

What I have tried:

Private Sub lstServers_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles lstServers.SelectedIndexChanged
      Dim ctrl As ListBox = DirectCast(sender, ListBox)

      ' SelectedItem was set to Nothing beforehand
      If ctrl.SelectedItem IsNot Nothing then
      ... do something ...
      End If
End Sub
Updated 14-Feb-19 8:01am

1 solution

You could remove the event from the handlers list and add it back at the end: Add and remove event handlers dynamically in VB.NET[^] That effectively "disables" it while it's being filled.
Share this answer
Sonhospa 14-Feb-19 14:45pm    
That seems to be exactly what I'm after, thank's a lot! This means I would instantiate the listBox without the "WithEvents" statement, and add the handler later, right?
OriginalGriff 15-Feb-19 2:07am    
That would be a lot clearer in the final code, yes.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900