How to get newly selected item of a ListBox with multiple selection?

I find that the ListBox control does not provide all functions that exist in its Windows native counterpart.

For example, I have a ListBox with SelectionMode set to MultiExtended. I need to know its index when a new item is selected. But I failed to find what events to handle.

Another less-used function is set focus rectangle to a selected item when a ListBox has more than one items selected.

Or I might be wrong.



Answer this question

How to get newly selected item of a ListBox with multiple selection?

  • TikiWan

    From MS Samples:
    ms-help://MS.VSCC.2003/MS.MSDNQTR.2005JAN.1033/cpref/html/frlrfSystemWindowsFormsSelectionModeClassTopic.htm



    Private Sub InitializeMyListBox()
       ' Add items to the ListBox.
       listBox1.Items.Add("A")
       listBox1.Items.Add("C")
       listBox1.Items.Add("E")
       listBox1.Items.Add("F")
       listBox1.Items.Add("G")
       listBox1.Items.Add("D")
       listBox1.Items.Add("B")

       ' Sort all items added previously.
       listBox1.Sorted = True

       ' Set the SelectionMode to select multiple items.
       listBox1.SelectionMode = SelectionMode.MultiExtended

       ' Select three initial items from the list.
       listBox1.SetSelected(0, True)
       listBox1.SetSelected(2, True)
       listBox1.SetSelected(4, True)

       ' Force the ListBox to scroll back to the top of the list.
       listBox1.TopIndex = 0
    End Sub

    Private Sub InvertMySelection()

       Dim x As Integer
       ' Loop through all items the ListBox.
       For x = 0 To listBox1.Items.Count - 1

          ' Determine if the item is selected.
          If listBox1.GetSelected(x) = True Then
             ' Deselect all items that are selected.
             listBox1.SetSelected(x, False)
          Else
             ' Select all items that are not selected.
             listBox1.SetSelected(x, True)
          End If
       Next x
       ' Force the ListBox to scroll back to the top of the list.
       listBox1.TopIndex = 0
    End Sub


     



  • AlbertS

    Thanks for DMan1's reply. But the code does not answer my question.

    Let me explain my problem in another way.

    Say I have listbox that has just three items - item1, item2 and item3. And SelectionMode is MultiExtended.

    I click on item1 and then hold down CTRL key and click on item3.

    Now I have a problem. The SelectedIndex property is 0 which is item1. I want to know the item that was just clicked on - it should be item3 and SelectedIndex should be 2.



  • How to get newly selected item of a ListBox with multiple selection?