65.9K
CodeProject 正在变化。 阅读更多。
Home

VB.Net 中的自动完成 ComboBox

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.63/5 (50投票s)

2002年4月22日

viewsIcon

535414

两个简单的函数,可以从 ComboBox 事件中调用以实现自动完成。适用于数据绑定的 ComboBox。

引言

这是一个自动完成 ComboBox,适用于 VB.NET 中的数据绑定或常规 ComboBox。在您键入时,大小写将被保留,但剩余文本将由列表项自动填充。当调用 Leave 函数时,大小写将被修正,并且如果列表中存在匹配项,则还将选择列表中的索引。

Sample Image - AutoComplete_ComboBox.gif

像这样从您的 ComboBox 的 KeyUpLeave 事件中调用相应的函数

Private Sub cboName_Leave(ByVal sender As Object, ByVal e As System.EventArgs) 
                                                            Handles cboName.Leave
    Dim recRowView As DataRowView
    Dim recName As DB.tblNameRow

    AutoCompleteCombo_Leave(cboName)

    'OPTIONAL: Now you can  do some extra handling if you want


    'Get the Selected Record from my Data Bound Combo (Return Type is DataRowView)

    recRowView = cboName.SelectedItem
    If recRowView Is Nothing Then Exit Sub

    'Display the Name Info (Row Type comes from my bound Dataset)

    recName = recRowView.Row
    lblAccountNum.Text = recName.AccountNum
    lblCompanyName.Text = recName.CompanyName

End Sub

Private Sub cboName_KeyUp(ByVal sender As Object, 
              ByVal e As System.Windows.Forms.KeyEventArgs) Handles cboName.KeyUp

    AutoCompleteCombo_KeyUp(cboName, e)

End Sub

以下是用于处理事件的通用函数

Public Sub AutoCompleteCombo_KeyUp(ByVal cbo As ComboBox, ByVal e As KeyEventArgs)
    Dim sTypedText As String
    Dim iFoundIndex As Integer
    Dim oFoundItem As Object
    Dim sFoundText As String
    Dim sAppendText As String

    'Allow select keys without Autocompleting

    Select Case e.KeyCode
        Case Keys.Back, Keys.Left, Keys.Right, Keys.Up, Keys.Delete, Keys.Down
            Return
    End Select

    'Get the Typed Text and Find it in the list

    sTypedText = cbo.Text
    iFoundIndex = cbo.FindString(sTypedText)

    'If we found the Typed Text in the list then Autocomplete

    If iFoundIndex >= 0 Then

        'Get the Item from the list (Return Type depends if Datasource was bound 

        ' or List Created)

        oFoundItem = cbo.Items(iFoundIndex)

        'Use the ListControl.GetItemText to resolve the Name in case the Combo 

        ' was Data bound

        sFoundText = cbo.GetItemText(oFoundItem)

        'Append then found text to the typed text to preserve case

        sAppendText = sFoundText.Substring(sTypedText.Length)
        cbo.Text = sTypedText & sAppendText

        'Select the Appended Text

        cbo.SelectionStart = sTypedText.Length
        cbo.SelectionLength = sAppendText.Length

    End If

End Sub


Public Sub AutoCompleteCombo_Leave(ByVal cbo As ComboBox)
    Dim iFoundIndex As Integer

    iFoundIndex = cbo.FindStringExact(cbo.Text)

    cbo.SelectedIndex = iFoundIndex

End Sub
© . All rights reserved.