'在您键入时自动滚动列表框

时间:2014-03-13 07:34:21

标签: vb.net listbox

我尝试为ListBox编写VB.Net代码,在其中键入时自动滚动列表框; 所以它会去,选择并突出显示与第一个相似的几个字母的项目; 下面的代码第一次工作正常(即表单加载时),但在此之后它停止工作; 有什么想法吗?

Public Class Form1

'AutoScroll Listbox as You Type 
Dim searchChars As String

Private Sub ListBox1_KeyUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles ListBox1.KeyUp
    searchChars += Chr(e.KeyValue)
    ListBox1.SelectedIndex = ListBox1.FindString(searchChars)
End Sub

Private Sub ListBox1_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles ListBox1.KeyPress
    e.Handled = True
End Sub


Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    ListBox1.Items.Add("Canada")
    ListBox1.Items.Add("USA")
    ListBox1.Items.Add("France")
    ListBox1.Items.Add("Japan")
    ListBox1.Items.Add("Belgium")
    ListBox1.Items.Add("Bulgariaa")
    ListBox1.Items.Add("India")
    ListBox1.Items.Add("Iraq")
    ListBox1.Items.Add("Iran")
    ListBox1.Items.Add("Ireland")
    ListBox1.Items.Add("Malaysia")
    ListBox1.Items.Add("Thailand")
    ListBox1.Items.Add("Bangaladish")
    ListBox1.Items.Add("Italy")
    ListBox1.Items.Add("Republic of Whatever")
End Sub


Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    ListBox2.Items.Add(ListBox1.SelectedItem)
    ListBox1.Focus()
End Sub

结束班

1 个答案:

答案 0 :(得分:0)

您在此处附加字符:

searchChars += Chr(e.KeyValue)

因此,如果您首先按I键,则会找到India,但如果您再次按I键,则searchChars将包含II,然后它无法找到任何项目以II开头,之后,您不会重置searchChars内的附加字符。

你可以这样做:

Private Sub ListBox1_KeyUp(ByVal sender As Object, ByVal e As KeyEventArgs) _
Handles ListBox1.KeyUp

    sender.SelectedIndex = 
           sender.FindString(Convert.ToChar(e.KeyValue), sender.SelectedIndex)

End Sub
  

更新:

另一种方法(附加字符):

Private Sub ListBox1_KeyUp(ByVal sender As Object, ByVal e As KeyEventArgs) _
Handles ListBox1.KeyUp

    Static SearchPattern As String
    SearchPattern &= CStr(Convert.ToChar(e.KeyValue))

    Dim FindIndex As Integer = 
        sender.FindString(SearchPattern)

    If FindIndex = -1 Then
        SearchPattern = CStr(Convert.ToChar(e.KeyValue))
        sender.SelectedIndex = sender.FindString(SearchPattern)

    Else
        sender.SelectedIndex = FindIndex

    End If

End Sub