I have a listbox with a hundred or so items. When the user clicks on the top or bottom item, I would like to automatically scroll the listbox so the selected item is centered.
When using the up/down arrows, the function works as desired, firing the Click event, where I change the TopIndex value to move the selected item to the center of the listbox.
However, when simply clicking the top/bottom item, the listbox is scrolled twice. My selected item ends up just above the top or just below the bottom of the listbox. I have included the code below, as it's not very long. Any help much appreciated.
When using the up/down arrows, the function works as desired, firing the Click event, where I change the TopIndex value to move the selected item to the center of the listbox.
However, when simply clicking the top/bottom item, the listbox is scrolled twice. My selected item ends up just above the top or just below the bottom of the listbox. I have included the code below, as it's not very long. Any help much appreciated.
Code:
Private Sub lbLST_Click()
Dim i%, f, l2%
Const lbLstLines = 16 ' computed elsewhere, hardcoded here
i = lbLST.ListIndex
If i < 0 Then Exit Sub
' Now we want to adjust the topIndex so if we clicked on the top
' or bottom entry, the listbox automatically centers the
' selection. That way we don't have to use the scrollbar as often.
' Works with up/down arrows, but not with mouse clicks!
l2 = lbLstLines / 2 ' half the lines displayed
Select Case lbLST.ListIndex
Case lbLST.TopIndex
noLstClick = True
If lbLST.TopIndex >= l2 Then
lbLST.TopIndex = lbLST.ListIndex - l2
Else
lbLST.TopIndex = 0
End If
Case lbLST.TopIndex + lbLstLines - 1
noLstClick = True
If lbLST.ListIndex + l2 < lbLST.ListCount Then
lbLST.TopIndex = lbLST.TopIndex + l2
Else
lbLST.TopIndex = lbLST.ListCount - 1
End If
End Select
End Sub