using mouse click and shift key in visual basic to select a range of items in a list box: selected index does not change

Ben Martinez 20 Reputation points
2023-01-23T23:49:05.8266667+00:00

I am updating a VB6 application to visual basic 2022. The application has a list box with data entries. I want to emulate the Explorer behavior of clicking on an item, then pressing shift and clicking on another item to select the range to copy it to the clipboard. I am able to select all by pressing CTRL+a. I have the following handler coded to select a range of items:

	Private Sub List1_Click(sender As Object, e As EventArgs) Handles List1.Click
		Dim SelIndx As Integer
		If FirstItem = -1 Then
			SelIndx = List1.SelectedIndex
			FirstItem = SelIndx
			List1.SetSelected(SelIndx, True)
		ElseIf My.Computer.Keyboard.ShiftKeyDown Then
			SelIndx = List1.SelectedIndex
			For i As Integer = FirstItem To SelIndx
				List1.SetSelected(i, True)
			Next
		End If
	End Sub

The variable FirstItem is defined in the class:
	Public FirstItem As Integer = -1

SelectionMode is set to MultiExtended

On clicking the second item I find that List1.SelectedIndex is still set to the index of the first item.  I saw an answer indicating the selected item index changes after updating the selected item, however I do not see how to update the item.  I do not want to change the item, I only want to select it for copy to clipboard.


VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,564 questions
{count} votes

Accepted answer
  1. LesHay 7,126 Reputation points
    2023-01-24T00:31:23.8266667+00:00

    Hi

    If I understand your question, see the code example below. Click drag to select a range, ctrl-click to select individually, shift click to select a range to clicked item. And any combination to select/deselect etc

    ' Form1 with ListBox1
    Option Strict On
    Option Explicit On
    Public Class Form1
      Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        With ListBox1
          .SelectionMode = SelectionMode.MultiExtended
          .Items.AddRange({"1", "2", "3", "4", "5"})
        End With
      End Sub
      Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim s As String = "Selection:" & vbCrLf
        For Each i As String In ListBox1.SelectedItems
          s &= i & ", "
        Next
        Clipboard.SetText(s)
        MessageBox.Show(s.Substring(0, s.Length - 2))
      End Sub
    End Class
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful