Private Sub CoBox1_TextChanged(sender As Object, e As EventArgs) Handles CoBox1.TextChanged
'获取输入的字符串
Dim text As String = CoBox1.Text.Trim()
'用以记录匹配字符串的个数
Dim index As Integer = 0
Dim listBox1 As New ListBox
' list_Pd是定义的全局布尔变量,用于判断是否创建了listbox控件
If list_pd Then '如果已经创建
For Each contr As Control In Me.Controls '遍历窗体中的所有控件,寻找创建的listbox控件
If contr.Name = "list" Then
listBox1 = CType(contr, ListBox)
End If
Next
Else '如果没有创建,则调用Custom_ListBox()函数创建
listBox1 = Custom_ListBox(CoBox1)
End If
'将listbox 控件所有项清空
listBox1.Items.Clear()
'将查询的结果添加到listbox 的items 中
For Each Str As String In CoBox1.Items
'将所有的字符串全部转化为小写再判断,这样输入就不用分大小写了
If Not text = "" And Str.ToLower.Contains(text.ToLower) Then
index += 1
listBox1.Items.Add(Str)
End If
Next
'判断符合条件的项的个数,
If index = 1 Then
CoBox1.Text = listBox1.Items(0)
listBox1.Visible = False
ElseIf index > 1 Then
listBox1.Visible = True
Else
listBox1.Visible = False
End If
listBox1.BringToFront()
End Sub
Private Function Custom_ListBox(ByVal CoBox1 As ComboBox) As ListBox
Dim Listbox As New ListBox
Dim point As Point
point.X = CoBox1.Location.X
point.Y = CoBox1.Location.Y + CoBox1.Height
With Listbox
.Name = "list" '设置控件名称
.Location = point '设置控件的位置,放在combobox的下面
.Width = CoBox1.Width '控件的宽度,与combobox的宽一样
.Height = CoBox1.Height * (CoBox1.Items.Count + 1) '高度
.Items.Clear()
.Visible = False
End With
AddHandler Listbox.Click, AddressOf ListBox_Click '添加点击事件 ListBox_Click()
Me.Controls.Add(Listbox) '这步重要 将控件添加到窗体中。没有这句将不会显示listbox控件
list_pd = True
Return Listbox
End Function
Private Sub ListBox_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
CType(sender, ListBox).Visible = False
CoBox1.Text = CType(sender, ListBox).SelectedItem
End Sub
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。