有界ComboBox自动完成排序

时间:2017-12-19 14:36:38

标签: vb.net 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 2005this question对于无界的Combobox。

1 个答案:

答案 0 :(得分:0)

我修改了this link中的代码,现在它可以根据需要运行:

s

我添加了这一行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 来解决this problem