Winform实现combox控件手动匹配查找,模糊查询功能

1.设置Combox属性: DropDownStyle:DropDown

2.添加TextUpdate事件

3.下列为Name = cb_material 的 combox 控件

private void cb_material_TextUpdate(object sender, EventArgs e)
        {
            string s = this.cb_material.Text;  //获取cb_material控件输入内容
            List<string> strList = new List<string>();   //存放原始数据(可以是对象,字符串...)
            strList.AddRange(materials.ToArray());  // List<string> materials 
            List<string> strListNew = new List<string>();
            //清空combobox
            this.cb_material.Items.Clear();
            //遍历全部原始数据
            foreach (var item in strList)
            {
                // 根据输入的值模糊查询,将符合条件的值存储到新strListNew的集合里面
                if (item.shape.Contains(this.cb_material.Text))
                {
                    strListNew.Add(item);
                }
            }
            if (strListNew.Count >= 1) // 存在符合条件的内容
            {
                //将符合条件的内容加到combobox中
                this.cb_material.Items.AddRange(strListNew.ToArray());
            }
            else  // 不存在符合条件时
            {
                // 下列代码为当查询不到符合的条件时新增自身输入的值
                // this.cb_material.Items.Add(this.cb_material.Text);
            }
            //设置光标位置,若不设置:光标位置始终保持在第一列,造成输入关键词的倒序排列
            this.cb_material.SelectionStart = this.cb_material.Text.Length;  // 设置光标位置,若不设置:光标位置始终保持在第一列,造成输入关键词的倒序排列
            Cursor = Cursors.Default; //保持鼠标指针原来状态,有时候鼠标指针会被下拉框覆盖,所以要进行一次设置
            this.cb_material.DroppedDown = true; // 自动弹出下拉框
        }

  

 

  

原文地址:https://www.cnblogs.com/besos/p/13355704.html