Winform實現combox控制元件手動匹配查詢,模糊查詢功能
阿新 • • 發佈:2020-07-21
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; // 自動彈出下拉框 }