martin_ljchan
martin_ljchan

Reputation: 1063

programmatically changing Combobox selection without causing the SelectedIndexChanged to fire

So I have a combobox with an event handler for SelectedIndexChanged:

    Private Sub cmbStatus_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbStatus.SelectedIndexChanged
        DoAnnoyingStuff()
        '....
    End sub

Elsewhere in my form, I have a function that does this (after some user interaction):

Sub RefreshStatus()
    Dim sel As Int32 = GetNewStatus()
    cmbStatus.SelectedIndex = sel   '<-- fires a SelectedIndexChanged event that I don't need
End Sub

What I want to do in RefreshStatus() is to change the selection shown in the combobox, but not execute DoAnnoyingStuff(). How do I do this?

Upvotes: 0

Views: 708

Answers (2)

SysDragon
SysDragon

Reputation: 9888

You can manually manage the event, enabling and disabling the handler with:

AddHandler cmbStatus.SelectedIndexChanged, AddressOf cmbStatus_SelIndexChg
RemoveHandler cmbStatus.SelectedIndexChanged, AddressOf cmbStatus_SelIndexChg    

And as said, you can use a flag:

Dim bRefreshStatus As Boolean = False

Private Sub cmbStatus_SelIndexChg(sender As Object, e As EventArgs) Handles cmbStatus.SelectedIndexChanged
    If Not bRefreshStatus Then DoAnnoyingStuff()
End Sub

Sub RefreshStatus()
    Dim sel As Int32 = GetNewStatus()
    bRefreshStatus = True
    cmbStatus.SelectedIndex = sel
    bRefreshStatus = False
End Sub

Upvotes: 1

Ian
Ian

Reputation: 4919

Add a flag. So you would have a private class field called _inChange As Boolean then set the field to true at the start of RefreshStatus, and false at the end. In cmbStatus_SelectedIndexChanged you check if _inChange is true. If it is you just exit. If false you continue and do AnnoyingStuff.

Upvotes: 1

Related Questions