.NET中为组合框添加自动查询功能

本文介绍了一种在窗体的组合框中实现自动完成功能的方法。通过两个自定义过程AutoCompleteKeyUp和AutoCompleteLeave,当用户在组合框中输入文字时,程序会自动匹配并显示最接近的选项,当焦点离开组合框时则调整所选内容的格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在窗体中添加如下方法:
第一个方法是AutoCompleteKeyUp,它将组合框和KeyEventArgs对象作为参数,需要在组合框的KeyUp事件中调用此方法;它全根据用户输入的内容选择最接近的内容;
第二个方法是AutoCompleteLeave在激活组合框的Leave事件时调用,此方法仅提取用户最终选择的内容,按照组合框中的每个匹配内容修改其大小写。
代码如下:
Private Sub AutoCompleteKeyUp(ByVal Combo As ComboBox, ByVal e As KeyEventArgs)
Dim strTyped As String
Dim intFoundIndex As Integer
Dim objFoundItem As Object
Dim strFoundText As String
Dim strAppendText As String
'忽略特殊键
Select Case e.KeyCode
Case Keys.Back, Keys.Left, Keys.Right, Keys.Up, Keys.Down, Keys.Delete, Keys.CapsLock
Return
End Select
'在查询列表中找到
strTyped = Combo.Text
intFoundIndex = Combo.FindString(strTyped)
If intFoundIndex >= 0 Then
objFoundItem = Combo.Items(intFoundIndex)
strFoundText = Combo.GetItemText(objFoundItem)
strAppendText = strFoundText.Substring(strTyped.Length)
Combo.Text = strTyped & strAppendText
Combo.SelectionStart = strTyped.Length
Combo.SelectionLength = strAppendText.Length
End If
End Sub
Private Sub AutoCompleteLeave(ByVal Combo As ComboBox)
Dim intFoundIndex As Integer
intFoundIndex = Combo.FindStringExact(Combo.Text)
Combo.SelectedIndex = -1
Combo.SelectedIndex = intFoundIndex
End Sub
Private Sub ComboBox1_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles ComboBox1.KeyUp
AutoCompleteKeyUp(ComboBox1, e)
End Sub
Private Sub ComboBox1_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles ComboBox1.Leave
AutoCompleteLeave(ComboBox1)
End Sub
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值