0
votes

I would like to deselect the last selected index if the user already selected more than 3 items (Only allow user to remove selections).

sender.selectedIndex returns the first selected listbox item and not the last (chronologically) one. Does anyone have any tips how I could achieve this?

example (* selected)

item1
*item2
item3
*item4
item5

if I select item3 then sender.selectedIndex contains item2 (first item) and sender.selectedItems contains item2,item3,item4 so I can't tell which one is new.

1
listBOX (from question text) or listVIEW (title) very big differenceŇɏssa Pøngjǣrdenlarp
Very sorry. I mean listbox but would also consider a listview if you can specify max 3 selected itemsLorof
The selectedItems collection stores the selections in the order that they appear in the listbox. I would like to get the last selected item (by time). I'll update the question.Lorof
sorry, I have one that does store them in order and forgot it was something I added. You'll have to create your own collection and update it as they select items.Ňɏssa Pøngjǣrdenlarp
So you have two collections (old and new) and compare them to get added items? Isn't that overkill for what should be really easy?Lorof

1 Answers

1
votes

You need to track and compare your own list against SelectedIndexes updating as needed. Apparently, the LB just iterates the items collection in order to build the Selecteditems collection, so it would always be in the same order as the items.

Is it overkill? Only if the app doesnt really need this level of detail. Otherwise, if you need it, you need it.

Private cList As New List(Of Integer)       ' our new Selected Indicies

Private Sub lb_SelectedIndexChanged(sender As Object, 
        e As EventArgs) Handles lb.SelectedIndexChanged

    Dim ndxCol As ListBox.SelectedIndexCollection
    ndxCol = lb.SelectedIndices

    ' add missing ones
    For Each n As Integer In ndxCol
        If cList.Contains(n) = False Then
            cList.Add(n)
        End If
    Next

    ' remove old ones
    For n As Integer = cList.Count - 1 To 0 Step -1
        If ndxCol.Contains(cList(n)) = False Then
            cList.Remove(cList(n))
        End If
    Next

End Sub