aaronsnoswell
aaronsnoswell

Reputation: 6251

MS Access: ListBox.Selected not working

I'm developing a database in MS Access 2013.

I have a form with a list box, and two buttons, btnNext and btnPrev - these buttons are used to change the currently selected item in the listbox. The user can also click in the listbox to change the selected item;

Picture of MS Access form

I would like to disable the 'previous' button when the user selects the first item in the list, and disable the 'next' button when the user selects the last item in the list. To do this, I have the following sub;

Private Sub UpdateNavigationButtons()

    If lstBox.Selected(0) Then
        btnPrev.Enabled = False
    Else
        btnPrev.Enabled = True
    End If

    If lstBox.Selected(lstBox.ListCount - 1) Then
        btnNext.Enabled = False
    Else
        btnNext.Enabled = True
    End If

End Sub

This Sub works fine when I call it from either of the button's Click event handlers or from the immediate window, but when I call it from the ListBox's AfterUpdate or Click event handlers, the .Selected array is always filled with zeroes. I can't find any documentation about this limitation on the MSDN documentation.

Can anyone suggest a way for me to disable these buttons when the user changes the current list box selection?

Upvotes: 1

Views: 4064

Answers (2)

Lenny Sockman
Lenny Sockman

Reputation: 101

For simply enabling/disabling the record selector buttons, I tried the following code and it worked for me. It also worked when the listbox had both a value list and table/query as the rowsource. You just call this code for the handlers and you're set. Hope that helps!

Private Sub UpdateListboxRecordSelectorButtons()

    Dim strMinValue As String
    Dim strMaxValue As String

    strMinValue = Me.lstResults.ItemData(0)
    strMaxValue = Me.lstResults.ItemData(Me.lstResults.ListCount - 1)

    Select Case Me.lstResults.Value
        Case strMinValue
            Me.cmdPrevious.Enabled = False
            Me.cmdNext.Enabled = True
        Case strMaxValue
            Me.cmdNext.Enabled = False
            Me.cmdPrevious.Enabled = True
        Case Else
            Me.cmdNext.Enabled = True
            Me.cmdPrevious.Enabled = True
    End Select

End Sub

Upvotes: 1

EliteRaceElephant
EliteRaceElephant

Reputation: 8162

There ist a distinct difference between ListBox.Selected and Listbox.ItemsSelected.

Listbox.Selected: https://msdn.microsoft.com/en-us/library/office/ff835338.aspx

ListBox.ItemsSelected: https://msdn.microsoft.com/en-us/library/office/ff823015.aspx

Could it be that you use the wrong function? Not sure if it is the case.

Upvotes: 0

Related Questions