C# Combobox控件实现模糊查询功能

8 篇文章 0 订阅

首先,先定义一个全局变量,用于存储Combobox中的数据
private List listCombobox;//Combobox的最初Item项
程序加载时,获取到Combobox中的Item项

private void MainForm_Load(object sender, EventArgs e)
{
listCombobox = getComboboxItems(this.comboBox1);//获取Item
}

//combobox的Text发生改变时调用此方法
private void comboBox1_TextUpdate(object sender, EventArgs e)
{
selectCombobox(comboBox1, listCombobox);
}

    #region 设置Combobox的方法
    //得到Combobox的数据,返回一个List
    public List<string> getComboboxItems(ComboBox cb){
        //初始化绑定默认关键词
        List<string> listOnit = new List<string>();
        //将数据项添加到listOnit中
        for (int i = 0; i < cb.Items.Count; i++)
        {
            listOnit.Add(cb.Items[i].ToString());
        }
        return listOnit;
    }
    //模糊查询Combobox
    public void selectCombobox(ComboBox cb, List<string> listOnit)
    {
        //输入key之后返回的关键词
        List<string> listNew = new List<string>();
        //清空combobox
        cb.Items.Clear();
        //清空listNew
        listNew.Clear();
        //遍历全部备查数据
        foreach (var item in listOnit)
        {
            if (item.Contains(cb.Text))
            {
                //符合,插入ListNew
                listNew.Add(item);
            }
        }
        //combobox添加已经查询到的关键字
        cb.Items.AddRange(listNew.ToArray());
        //设置光标位置,否则光标位置始终保持在第一列,造成输入关键词的倒序排列
        cb.SelectionStart = cb.Text.Length;
        //保持鼠标指针原来状态,有时鼠标指针会被下拉框覆盖,所以要进行一次设置
        Cursor = Cursors.Default;
        //自动弹出下拉框
        cb.DroppedDown = true;
    } 
    #endregion

————————————————
版权声明:本文为CSDN博主「zjz199303」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/zjz199303/article/details/50507731

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值