mandroid
mandroid

Reputation: 2328

Limit number of selections in a MultiSelect ListBox

Is there a way to limit the number of selections a user can choose on a ListBox with MultiSelect enabled in Access 2003? Right now I have a procedure that fires on the On Click event that checks the number of choices selected and if it is over my threshold it will display a warning label.

Upvotes: 2

Views: 10293

Answers (4)

Fink
Fink

Reputation: 3436

Give this a try. It basically deselects the last item selected if its over the predefined limit:

Private Sub ListBox1_Change()

Dim counter         As Integer
Dim selectedCount   As Integer

selectedCount = 0

For counter = 1 To ListBox1.ListCount Step 1
    If ListBox1.Selected(counter - 1) = True Then 'selected method has 0 base
        selectedCount = selectedCount + 1
    End If
Next counter

If selectedCount >= 4 Then 'modify # here
    ListBox1.Selected(ListBox1.ListIndex) = False 'listindex returns the active row you just selected
    MsgBox "Limited to 4 Choices", vbInformation + vbOKOnly, "Retry:"
End If
End Sub

Upvotes: 5

Marcand
Marcand

Reputation: 314

You can use the listbox BeforeUpdate event to see the listbox.ItemsSelected.Count value. If this is over your limit then you unselect (with listbox.Selectec(item)=False) the current one and cancel the event.

Here's an example : Private Sub lstItems_BeforeUpdate(Cancel As Integer)

' Warn the user that only x items can be selected.
' ------------------------------------------------
If lstItems.ItemsSelected.Count > MAX_SELECTED_ITEM_PERMITTED Then
    MsgBox "You can only select " & MAX_SELECTED_ITEM_PERMITTED & " items in this list.", vbOKOnly + vbInformation, "Error"

    ' Unselect previously selected item.
    ' ----------------------------------
    lstItems.Selected(lstItems.ListIndex) = False
    Cancel = True
End If
End Sub

Upvotes: 3

David-W-Fenton
David-W-Fenton

Reputation: 23067

I would suggest that a much more manageable, user-friendly and understandable UI for this would be the paired listbox approach, with ADD> and button after the user has reached the limit. You don't have to do anything difficult, just check the ListCount of the right-hand listbox and disable the ADD> button when it reaches the limit.

And you avoid many problems as it's quite clear to the user what they are doing in comparison to selecting multiple items at once in a single listbox. You could make the lefthand listbox multiselect and simply disable the ADD> button if the ItemsSelected count exceeds the limit, and notify the user appropriately.

Upvotes: 1

Tony Toews
Tony Toews

Reputation: 7882

Using the listbox ItemsSelected collection? That's the only way that I know of to limit the number of selected items. OTOH there are some truly twisted individuals out there who might have figured out an alternative so I never say never.

What's the problemw with this method?

Upvotes: 1

Related Questions