Private Sub CoBox1_TextChanged(sender As Object, e As EventArgs) Handles CoBox1.TextChanged '獲取輸入的字符串 Dim text As String = CoBox1.Text.Trim() '用以記錄匹配字符串的個數(shù) Dim index As Integer = 0 Dim listBox1 As New ListBox ' list_Pd是定義的全局布爾變量,,用于判斷是否創(chuàng)建了listbox控件 If list_pd Then '如果已經(jīng)創(chuàng)建 For Each contr As Control In Me.Controls '遍歷窗體中的所有控件,,尋找創(chuàng)建的listbox控件 If contr.Name = "list" Then listBox1 = CType(contr, ListBox) End If Next Else '如果沒有創(chuàng)建,,則調(diào)用Custom_ListBox()函數(shù)創(chuàng)建 listBox1 = Custom_ListBox(CoBox1) End If '將listbox 控件所有項清空 listBox1.Items.Clear() '將查詢的結(jié)果添加到listbox 的items 中 For Each Str As String In CoBox1.Items '將所有的字符串全部轉(zhuǎn)化為小寫再判斷,這樣輸入就不用分大小寫了 If Not text = "" And Str.ToLower.Contains(text.ToLower) Then index += 1 listBox1.Items.Add(Str) End If Next '判斷符合條件的項的個數(shù),, 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" '設(shè)置控件名稱 .Location = point '設(shè)置控件的位置,,放在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
|
|