从网上找到了一种非datasource数据源的查询如combox1的填充方式,因为现在用的都是datasource的数据源,所以又改进了下如combox2的填充方式,如果不增加改变事件都是可以从左查询的。
public partial class Form3 : Form
{
//初始化绑定默认关键词(此数据源可以从数据库取)
List<string> listOnit = new List<string>();
//输入key之后,返回的关键词
List<string> listNew = new List<string>();
DataTable dt = new DataTable();
public Form3()
{
InitializeComponent();
}
private void Form3_Load(object sender, EventArgs e)
{
BindComboBox();
BindComboBox1();
}
/// <summary>
/// 绑定ComboBox
/// </summary>
private void BindComboBox()
{
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());
}
private void BindComboBox1()
{
dt.Columns.Add("id", typeof(System.String));
dt.Columns.Add("name", typeof(System.String));
DataRow dr = dt.NewRow();
dr[0] = "0";
dr[1] = "张三";
dt.Rows.Add(dr);
DataRow dr1 = dt.NewRow();
dr1[0] = "1";
dr1[1] = "张五";
dt.Rows.Add(dr1);
DataRow dr2 = dt.NewRow();
dr2[0] = "2";
dr2[1] = "马六";
dt.Rows.Add(dr2);
this.comboBox2.DataSource = dt;
this.comboBox2.DisplayMember = "name";
this.comboBox2.ValueMember = "id";
自动完成数据源
this.comboBox2.AutoCompleteSource = AutoCompleteSource.CustomSource;
提示类型 建议列表+自动补全
this.comboBox2.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
绑定数据源
string[] wb = new string[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
wb[i] = dt.Rows[i]["name"].ToString();
}
this.comboBox2.AutoCompleteCustomSource.AddRange(wb);
}
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;
}
private void comboBox2_TextUpdate(object sender, EventArgs e)
{
string strsearch = this.comboBox2.Text.ToString();
this.comboBox2.DataSource = null;
this.comboBox2.Items.Clear();
DataView dt1 = new DataView();
dt1 = dt.DefaultView;
dt1.RowFilter = "name like '%" + strsearch + "%'";
this.comboBox2.DataSource = dt1;
this.comboBox2.DisplayMember = "name";
this.comboBox2.ValueMember = "id";
Cursor = Cursors.Default;
this.comboBox2.Text = strsearch;
this.comboBox2.SelectionStart = strsearch.Length;
//自动弹出下拉框
this.comboBox2.DroppedDown = true;
}
}