KARA
KARA

Reputation: 1

Going to the letter printed on the keyboard in Listbox is there in Listview?

Going to the letter pressed on the keyboard in Listbox is there in Listview? When I press the keyboard key to access items in the list view sub-item, I want it to select the ones that match the first letter. Like a list box.

Upvotes: 0

Views: 56

Answers (1)

Mary
Mary

Reputation: 15091

The ListBox must have focus for this to work. You can set the ActiveControl of the Form or the user can tab to the control or click in the ListBox. You can also call ListBox.Focus() but not from the Form events.

The key pressed is returned by KeyChar and is case sensitive. The items in ListBox.Items are Objects so we need to call .ToString to be able to compare them with letter. Strings are really array of Char. We can use the Linq .First method on this array to get the first Char in the array. Then we .Add or .Remove the item from the SelectedItems collection.

Private lst As New List(Of String) From {"Mathew", "Mark", "Luke", "John"}

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    'Be sure you have multiple select set - this can be done at design time
    ListBox1.SelectionMode = SelectionMode.MultiSimple
    ListBox1.DataSource = lst
    'Clears the default selection of the first item
    ListBox1.SelectedIndex = -1
    'The ListBox must have focus to the key press code to work
    ActiveControl = ListBox1
End Sub

Private Sub ListBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles ListBox1.KeyPress
    Dim letter = e.KeyChar
    For i = 0 To ListBox1.Items.Count - 1
        If ListBox1.Items(i).ToString.First = letter Then
            ListBox1.SelectedItems.Add(ListBox1.Items(i))
        Else
            ListBox1.SelectedItems.Remove(ListBox1.Items(i))
        End If
    Next
End Sub

EDIT

As per comment, check out the FindItemWithText and FindNearestItem methods of the ListView. There are several overloads. See https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.listview?view=net-5.0

Upvotes: 1

Related Questions