hey123
hey123

Reputation: 5

Prevent Code Running if Combobox's SelectedIndex was Never Changed

I have a combo box that has a couple items in them, where they add text to a text box. I want to prevent the same item being selected twice in a row, because the index never changed, but it still runs the code.

Here's what I've done:

    Dim intComboIndex As Integer = -1
    Dim cboComboBox As ComboBox = CType(sender, ComboBox)
    Dim intComboSelIndex As Integer = cboComboBox.SelectedIndex
    If intComboSelIndex > -1 And intComboSelIndex <> intComboIndex Then intComboIndex = intComboSelIndex

Is there a more efficient way of doing this, without having to create a different combo box and compare the indexes?

Upvotes: 0

Views: 60

Answers (1)

Visual Vincent
Visual Vincent

Reputation: 18310

You must store the previously selected index elsewhere, because at the moment you recreate the variable every time the event is raised.

I'd recommend storing the previously selected index at class level, and then compare that to the currently selected index.

Public Class Form1
    Dim ComboBoxPrevIndex As Integer = -1 'Declared at class level, outside any Sub or Function.

    Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
        Dim SenderBox As ComboBox = DirectCast(sender, ComboBox) 'Get the control that raised the ever.

        'Has the selection changed?
        If ComboBoxPrevIndex <> SenderBox.SelectedIndex _
            AndAlso SenderBox.SelectedIndex > -1 Then
            'Do stuff...
        End If

        ComboBoxPrevIndex = SenderBox.SelectedIndex 'Set the new, previous index.
    End Sub
End Class

You might have noticed that I used AndAlso instead of And. This is because of AndAlso is short-circuited, meaning that it will only check the condition on it's right if the condition on it's left evaluates to True.

Upvotes: 1

Related Questions