分享

方法脚本2:组合框comboBox和listbox配合模糊查询显示

 xzx淘淘 2019-04-19
 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

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多