有界ComboBox自动完成排序
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了有界ComboBox自动完成排序相关的知识,希望对你有一定的参考价值。
我有一个有界的Combobox,它的数据源已经排序,但似乎在我开始输入时自动完成对其项目的重新排序。
例如,我使用此代码:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dt As New DataTable
With dt
.Columns.Add("id", GetType(Long))
.Columns.Add("Name", GetType(String))
.Rows.Add({1, "John"})
.Rows.Add({2, "Jan"})
End With
With Me.ComboBox1
.DataSource = dt
.ValueMember = "id"
.DisplayMember = "Name"
.DropDownStyle = ComboBoxStyle.DropDown
.AutoCompleteMode = AutoCompleteMode.SuggestAppend
.AutoCompleteSource = AutoCompleteSource.ListItems
End With
End Sub
现在当我输入j
时,Combobox建议Jan
,但我想要第一个项目John
。
对于无界的Combobox,这是有效的:How to provide automatic text completion for a ComboBox control in Visual Basic .NET or in Visual Basic 2005和this question是无限的Combobox。
答案
我修改了this link中的代码,现在它可以根据需要工作:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dt As New DataTable
With dt
.Columns.Add("id", GetType(Long))
.Columns.Add("Name", GetType(String))
.Rows.Add({1, "John"})
.Rows.Add({2, "Jan"})
End With
With Me.ComboBox1
.DataSource = dt
.ValueMember = "id"
.DisplayMember = "Name"
.DropDownStyle = ComboBoxStyle.DropDown
.AutoCompleteMode = AutoCompleteMode.None
End With
End Sub
Private Sub ComboBox1_KeyUp(sender As Object, e As KeyEventArgs) Handles ComboBox1.KeyUp
' Do nothing for some keys such as navigation keys.
If ((e.KeyCode = Keys.Back) Or
(e.KeyCode = Keys.Left) Or
(e.KeyCode = Keys.Right) Or
(e.KeyCode = Keys.Up) Or
(e.KeyCode = Keys.Delete) Or
(e.KeyCode = Keys.Down) Or
(e.KeyCode = Keys.PageUp) Or
(e.KeyCode = Keys.PageDown) Or
(e.KeyCode = Keys.Home) Or
(e.KeyCode = Keys.End)) Then
Return
End If
Dim actual As String = Me.ComboBox1.Text
Dim dt As DataTable = Me.ComboBox1.DataSource
Dim dr = dt.Select("Name like '" & actual & "%'")
If dr.Count > 0 Then
Dim found As String
With Me.ComboBox1
.DroppedDown = True
Cursor.Current = Cursors.Default 'to show the cursor again
found = dr(0)("Name")
.Text = found
.SelectionStart = actual.Length
.SelectionLength = found.Length
End With
End If
End Sub
我添加了这行Cursor.Current = Cursors.Default
来解决this problem。
以上是关于有界ComboBox自动完成排序的主要内容,如果未能解决你的问题,请参考以下文章
C# WinForms ComboBox:AutoComplete 不按降序排序