winform中combobox下拉框模糊查询、搜索

该博客介绍了如何在C#中实现ComboBox的动态搜索功能。通过设置DropDown样式,监听TextUpdate事件,从数据库获取原始数据,并在用户输入时进行模糊匹配,实时更新ComboBox的显示内容。同时,代码还处理了光标位置和下拉框显示的问题,确保用户友好体验。

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

结果如图

在这里插入图片描述

先让combobox可以修改

  list.DropDownStyle = ComboBoxStyle.DropDown;
  

然后创建combobox的文本修改事件

     private void ComCB_TextUpdate(object sender, EventArgs e)
        {
            List<string> strList = new List<string>();   //存放原始数据(可以是对象,字符串...)
            foreach (var item in DataUtil.GetVendor())//数据库中获取的原始数据 
            {
                strList.Add(item[1]);//第一列是名称
            }
            Cursor = Cursors.Default; //保持鼠标指针原来状态,有时候鼠标指针会被下拉框覆盖,所以要进行一次设置
            DataUtil.TextUpdate(this.ComCB, strList);

        }

其次创建TextUpdate方法

 /// <summary>
        /// combobox搜索功能
        /// </summary>
        /// <param name="cb"></param>
        /// <param name="strList"></param>
        public static void TextUpdate(ComboBox cb, List<string> strList)
        {
            string s = cb.Text;  //获取cb_material控件输入内
            List<string[]> strListNew = new List<string[]>();
            //清空combobox
            cb.DataSource = null;
            cb.Items.Clear();
            //遍历全部原始数据
            foreach (var item in strList)
            {
                // 根据输入的值模糊查询,将符合条件的值存储到新strListNew的集合里面
                if (item.Contains(s))
                {
                    strListNew.Add(new string[] { "", item });
                }
            }
            if (strListNew.Count >= 1) // 存在符合条件的内容
            {
                //将符合条件的内容加到combobox中
                //this.ComCB.Items.AddRange(strListNew.ToArray());
                DataUtil.GetComCB(cb, strListNew);
            }
            // 不存在符合条件时
            //设置光标位置,若不设置:光标位置始终保持在第一列,造成输入关键词的倒序排列
            cb.SelectionStart = cb.Text.Length;  // 设置光标位置,若不设置:光标位置始终保持在第一列,造成输入关键词的倒序排列
            //cb.Cursor = Cursors.Default; //保持鼠标指针原来状态,有时候鼠标指针会被下拉框覆盖,所以要进行一次设置
            cb.DroppedDown = true; // 自动弹出下拉框
            cb.MaxDropDownItems = 8; // 自动弹出下拉框

        }

最后写入数据

  /// <summary>
        /// 设置combobox的item值
        /// </summary>
        /// <param name="cb">ComboBox</param>
        public static void GetComCB(ComboBox cb, List<string[]> res)
        {
            ArrayList mylist = new ArrayList();
            foreach (var item in res)
            {
                mylist.Add(item[1]);
            }
            cb.Items.AddRange(mylist.ToArray());
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值