最近朋友問了一個關於Winform實現ComboBox模糊查詢的知識點,自己好久沒有搞Winform了,就上手練了一下,廢話不多說,進入正題。
前台設計:
前台就是一個簡單的Form窗體+一個ComboBox控件。
思路整理:
1.用一個List<string> listOnit存放初始化數據,用一個List<string> listNew存放輸入key之后,返回的數據。
2.用上面的listOnit初始化ComboBox數據源進行綁定。
3.在TextUpdate方法內部,添加實現方法。
首先進入方法,先清除ComboBox的內容,然后將輸入的內容去listOnit初始化的數據中比對,找出對應數據,然后放入listNew存放數據,最后將listNew數據重新賦值給 ComboBox。
后台代碼實現:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace TimerDemo { public partial class Form2 : Form { //初始化綁定默認關鍵詞(此數據源可以從數據庫取) List<string> listOnit = new List<string>(); //輸入key之后,返回的關鍵詞 List<string> listNew = new List<string>(); public Form2() { InitializeComponent(); } private void Form2_Load(object sender, EventArgs e) { //調用綁定 BindComboBox(); } /// <summary> /// 綁定ComboBox /// </summary> private void BindComboBox() { listOnit.Add("張三"); listOnit.Add("張思"); listOnit.Add("張五"); listOnit.Add("王五"); listOnit.Add("劉宇"); listOnit.Add("馬六"); listOnit.Add("孫楠"); listOnit.Add("那英"); listOnit.Add("劉歡"); /* * 1.注意用Item.Add(obj)或者Item.AddRange(obj)方式添加 * 2.如果用DataSource綁定,后面再進行綁定是不行的,即便是Add或者Clear也不行 */ this.comboBox1.Items.AddRange(listOnit.ToArray()); } private void comboBox1_TextChanged(object sender, EventArgs e) { /* * 不能用TextChanged操作,當this.comboBox1.DroppedDown為True時,選擇項上下鍵有沖突 */ } private void comboBox1_TextUpdate(object sender, EventArgs e) { //清空combobox this.comboBox1.Items.Clear(); //清空listNew listNew.Clear(); //遍歷全部備查數據 foreach (var item in listOnit) { if (item.Contains(this.comboBox1.Text)) { //符合,插入ListNew listNew.Add(item); } } //combobox添加已經查到的關鍵詞 this.comboBox1.Items.AddRange(listNew.ToArray()); //設置光標位置,否則光標位置始終保持在第一列,造成輸入關鍵詞的倒序排列 this.comboBox1.SelectionStart = this.comboBox1.Text.Length; //保持鼠標指針原來狀態,有時候鼠標指針會被下拉框覆蓋,所以要進行一次設置。 Cursor = Cursors.Default; //自動彈出下拉框 this.comboBox1.DroppedDown = true; } } }
實現效果截圖:
從左到右模糊查詢:(例如輸入:張)
可以得出正常模糊查詢的結果。
不是從左到右模糊查詢呢?(例如輸入:三)
也可以查詢到想要的數據,OK,完成。
實現過程中的問題:
1.綁定數據一開始用的DataSource方式,但是寫到下面重新給ComboBox設置數據源的時候,報錯:不能為已經設置DataSource的combobox賦值。
解決方式:將賦值方式改為:Item.Add(obj)或者Item.AddRange(obj)方式
2.下拉框的內容一直在增加
解決方式:當文本框文本改變時,清空下拉框的內容,然后再添加數據。
3.輸入文本改變時,沒有自動彈出下拉框顯示已經查詢好的數據。
解決方式:設置comboBox的DroppedDown 屬性為True。
4.ComboBox文本框改變事件一開始選擇用的是TextChanged事件,但是當在界面用 上 下鍵盤選擇時,出現bug,不能進行選擇。
解決方式:將文本框改變事件換為TextUpdate事件,然后添加實現方法。
5.當在ComboBox輸入內容時,內容文本是倒序輸出的,光標位置始終在最前面。
解決方式:設置光標的顯示位置,this.comboBox1.SelectionStart = this.comboBox1.Text.Length;
6.輸入內容改變時,用鼠標選擇下拉列表項的時候,鼠標指針消失,被下拉框覆蓋掉。
解決方式:設置鼠標狀態為一開始的默認狀態,Cursor = Cursors.Default;