上一篇文章是用ComboBox里面的原生事件實現模糊查詢,操作比較靈活一些,但是收到評論說,利用AutoComplete屬性就可以實現模糊查詢,但是據本人所了解,AutoComplete雖然能夠方便的實現模糊查詢,但是有一定的缺陷,就是,模糊查詢只能從左往右。
上一篇連接地址:http://www.cnblogs.com/xilipu31/p/3993049.html
下面是簡單的實現方式:
前台:一個簡單的form窗體+ComboBox控件
后台:申明List<string> listOnit用於初始化ComboBox的備選數據,然后設置ComboBox屬性:AutoCompleteSource(自動完成數據源),AutoCompleteMode(提示類型)以及AutoCompleteCustomSource(綁定數據源)。
具體代碼如下:
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 Form3 : Form
{
//初始化綁定默認關鍵詞(此數據源可以從數據庫取)
List<string> listOnit = new List<string>();
public Form3()
{
InitializeComponent();
}
private void Form3_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("劉歡");
//自動完成數據源
this.comboBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
//提示類型 建議列表+自動補全
this.comboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
//綁定數據源
this.comboBox1.AutoCompleteCustomSource.AddRange(listOnit.ToArray());
}
}
}
以下是實現效果截圖:
從左到右輸入關鍵詞模糊查詢(例如輸入:張)

可以得出正確的提示和結果。
如果不是從左到右的模糊查詢呢?(例如輸入:三)

可以看出,並不能將模糊數據查詢出來。
總結:
ComboBox控件的AutoComplete事件可以用在模糊查詢程度不高,從左到右的關鍵詞搜索,如果想實現高級的模糊查詢,還是自己定義的方式比較靈活一些。
